This appendix provides worked solutions for analytical end-of-chapter exercises and guidance for coding exercises. Coding exercises (those that ask the reader to modify a notebook or measure a numerical quantity) are not treated as fixed numerical answers; their outputs depend on hardware, seeds, calibration choices, and notebook versions, and should be reported from the corresponding companion notebook listed in the Execution Map. For exercises that mix analytical work with a small numerical check, the analytical part is solved and the numerical component is described as a verification task.
Exercises are referenced by their stable label ex:ch:, where is the chapter number and is the position within that chapter’s exercise list. Each solution opens with a back-pointer to the exercise statement so the reader can scan the question first.
F.0.1Chapter Chapter 1: Introduction to Machine Learning and Deep Learning¶
F.0.1.1Exercise 1.1: Backprop on a 2-layer net.¶
Let , , , . Reverse-mode chain rule:
Plugging in , , : , , , . Hence and . A two-line PyTorch script (torch.autograd.grad) returns the same numbers to machine precision; this is the simplest non-trivial sanity check that the chain-rule derivation matches what AD computes.
F.0.1.2Exercise 1.2: MSE vs. MLE.¶
For Gaussian errors , the log-likelihood is
Maximizing over (the only -dependent term) is identical to minimizing , i.e. OLS. For Laplace errors with scale , , so the log-likelihood is proportional to and the MLE solves a least-absolute-deviations regression (median regression). Squaring penalizes outliers quadratically, which is suboptimal under Laplace tails because a single large residual dominates the loss; the median estimator is robust precisely because grows linearly.
F.0.1.3Exercise 1.3: Activation choice for a PINN.¶
A ReLU network is piecewise-linear: between consecutive kink points it is affine in , so on every open subinterval. At a kink, the second distributional derivative is a Dirac measure, not a classical pointwise value. A strong-form PDE residual such as the Black--Scholes operator
must hold pointwise (a.e.) for almost every ; with a piecewise-linear , the term vanishes a.e. in the classical sense, and the residual reduces to , which has no nontrivial solution that respects the actual boundary conditions of an option-pricing problem. Concrete example: has for every in the classical sense. Smooth activations (tanh, Swish, GELU, softplus) are and produce well-defined pointwise second derivatives, which is why the PINN literature recommends them whenever the PDE is of order .
F.0.1.4Exercise 1.4: Adam vs. AdamW.¶
Write the gradient at step as . With regularization added to the loss, , so the effective gradient becomes . Adam’s update applied to is
The key observation is that the weight-decay contribution enters and through the same EWMA averaging as the data gradient, so the effective shrinkage applied to is scaled by , which differs across coordinates. Parameters with large historical gradients receive small effective decay; parameters with small gradients receive large decay. AdamW decouples the two:
Now the multiplicative shrinkage acts uniformly on all parameters, independent of the adaptive denominator. Numerically the two updates differ by a factor of on the decay term; AdamW preserves the textbook intuition “weight decay shrinks weights at the same rate everywhere.”
F.0.1.5Exercise 1.5: RNN forward pass by hand.¶
With , , :
Outputs: gives , , (only the first hidden coordinate is excited, so the second column of is irrelevant).
For the gradient, write with . Then
where . Numerically, , , , so
The decay rate is the product of two distinct effects: (i) the spectral radius of (here 0.5), which contributes one factor of per recurrent step ( multiplicative copies in the chain above), and (ii) the saturation of , which contributes a second multiplicative factor per step. Setting (ii) aside, with the gradient magnitude already decays at least as fast as , i.e. exponentially in the sequence length. This is the canonical vanishing-gradient pathology of vanilla RNNs (Section 1.11). LSTM and GRU gates address (i) by allowing the recurrent Jacobian’s eigenvalues to stay close to one without making training unstable; effect (ii) is intrinsic to bounded activations and is mitigated by skip connections (and architectural choices that keep activations away from saturation regimes), not by gating.
F.0.1.6Exercise 1.6: Attention by hand.¶
With and , the score matrix is
Softmaxing each row and using , , , :
Each attention vector is on the simplex (entries non-negative, summing to one), so is a convex combination of the values, lying in . Token 2, the largest input, attends most strongly to itself (); token 3 also attends most to token 2 because the inner products exceed the self-score . Token 1 has zero query magnitude, so its row is uniform: with no signal to discriminate on, attention defaults to a uniform average over the values.
F.0.1.7Exercise 1.7: TensorBoard optimizer comparison.¶
Coding exercise. Expected qualitative behavior on a small classification task: SGD with momentum is often slower to reduce training loss but can generalize competitively when the learning-rate schedule is well tuned; Adam often reaches a low training loss fastest, but its validation curve can diverge from the training curve sooner than for SGD or AdamW; AdamW often sits between the two. The actual crossover point is a notebook output and should be reported from the run.
F.0.2Chapter Chapter 2: Deep Equilibrium Nets¶
F.0.2.1Exercise 2.1: Closed-form Brock--Mirman.¶
Conjecture . The Bellman equation
yields the FOC , which gives the constant savings rate
Substituting the conjecture back and matching the coefficient produces , hence . Plugging this into :
The DEQN parameterizes . Once converged, the average sigmoid output across the ergodic set should equal (typical calibrations , give ). Any systematic deviation indicates either insufficient training or a quadrature / sampling bias.
F.0.2.2Exercise 2.2: Hard vs. soft constraints.¶
With a softplus head on consumption alone, is guaranteed, but next-period capital is then defined as the residual , which is unconstrained in sign. At random initialization the network output is approximately , so is approximately on average but can be much larger.
Concrete failure: take , , , so . If the network produces an output of, say, 5, then and . The next iterate is then complex, and the loss explodes.
The sigmoid-savings parameterization avoids this entirely: and both hold by construction, regardless of the network’s raw output. This is the simplest example of the broader principle that architectural feasibility encodings dominate loss-based ones whenever the constraint can be written as a closed-form algebraic identity.
F.0.2.3Exercise 2.3: Path averaging vs. conditional expectation.¶
On the simulated path, the path-averaged residual is with generated by the model dynamics. Under ergodicity, Birkhoff’s theorem gives
where is the stationary distribution. The conditional-expectation residual at a fixed point , , is a different object: it integrates only over the conditional shock distribution, holding the current state fixed.
Their connection: if one sweeps the conditional residual over and averages, the result coincides with by the law of iterated expectations. In other words, path averaging combines sampling over states (the outer expectation) and the implicit Monte Carlo integration over shocks (one shock per simulated step). Conditional expectation evaluates the inner integral exactly via quadrature but still requires a way to draw states .
Bias--variance trade-off at finite : the path-averaged loss has variance from finite-sample noise but no bias. An exact-quadrature residual has zero stochastic noise on the inner integral but its outer-state coverage depends on the sampling scheme; with mini-batch SGD over the ergodic set, the variance comes from the random batch, not the integration. In the chapter the deterministic quadrature is preferred whenever the shock dimension is low (), and pathwise residuals dominate once is high enough that explicit quadrature becomes expensive.
F.0.2.4Exercise 2.4: Brock--Mirman with Gauss--Hermite.¶
The Euler equation in Brock--Mirman with , log utility, and AR(1) productivity , , is
Replace the expectation by a Gauss--Hermite rule. After the change of variables that absorbs the normalization , the -point GH quadrature is
with classical nodes and weights that satisfy . Table Table F.1 lists the five-point rule used in this exercise.
Table F.1:Five-point Gauss--Hermite nodes and weights for the convention . The weights sum to before the outside normalization.
| 1 | -2.0202 | 0.0200 |
| 2 | -0.9586 | 0.3936 |
| 3 | 0.0000 | 0.9453 |
| 4 | +0.9586 | 0.3936 |
| 5 | +2.0202 | 0.0200 |
Substituting, the residual at a state becomes
where and is the consumption obtained by feeding into the network. Numerically, comparing this 5-point sum with a high-draw Monte Carlo estimate on the same residual is a useful diagnostic: agreement should be close for smooth integrands and small shock variance, but the realized discrepancy is an output of the check rather than a fixed benchmark.
F.0.2.5Exercise 2.5: Monomial rule by hand (Stroud-3 at ).¶
Equation (2.18) places nodes at for , with equal weights . At , the eight nodes are for .
First moment. by ±-cancellation.
Second moment. is non-zero only at , where it equals . Two such nodes contribute , weighted by , giving exactly 1.
Cross moment. for is zero at every node because each node has only one nonzero coordinate. So the rule returns 0, the true value.
Third moment. at equals ; the two values cancel. Returns 0, exact.
Fourth moment. at equals , both signs. Two nodes contribute , weighted by , gives . At , the rule returns 4, while the true value .
Linear bias growth. In general the rule reports for the fourth moment, so the relative error is linear in : at , at , doubles to 1 () at .
When does this matter? The Euler residual is a smooth function of the next-period shock . Taylor-expanding around the conditional mean, the leading bias term is the Hessian of the residual with respect to , which probes the second moment, exact under Stroud-3. Fourth-moment bias enters only at the next order, scaled by the integrand’s fourth derivative. For moderate CRRA curvature and thin-tailed shocks this term can be small relative to classroom residual tolerances, but it is a diagnostic to check rather than a universal bound. The bias becomes material when (i) the integrand has heavy fourth-order content (e.g., very risk-averse preferences or fat-tailed shocks), or (ii) the shock dimension is large enough that the relative error exceeds the residual tolerance one targets. This is the threshold at which the monomial rule should be replaced by Stroud-5 ( nodes) or QMC.
F.0.2.6Exercise 2.6: Loss-kernel selection.¶
Definitions for reference. MSE: . MAE: . Huber(): quadratic for , linear above. Pinball loss at : , whose minimizer is the -quantile of . CVaR at : the expected value of conditional on exceeding its -quantile. Log-cosh: , smooth and quadratic near zero, linear in tails.
(a) Huber loss: “smooth, quadratic near zero, linear in tails” is the literal definition. MAE is also linear-in-tails but is not differentiable at , so its gradient flips discontinuously and the optimizer stalls; log-cosh is smooth and shares the asymptotic shape with Huber but has no tunable threshold. Huber() gives the cleanest control of where the regime change happens.
(b) CVaR at . The CVaR loss optimizes the conditional mean above the 99th-percentile threshold, which is exactly what the regulator audits. The pinball loss at would only target the 99th-percentile residual itself, not the conditional average above it; if the residuals have a fat right tail, the pinball-trained policy can have arbitrarily large worst-case residuals. CVaR is the right primitive for “worst-case mean” control.
(c) MAE (or equivalently pinball at ). By construction MAE’s first-order condition is solved at the median, not the mean: , so the gradient contribution is per residual, regardless of magnitude. This is exactly what the desideratum asks for, no single tail residual dominates the gradient. Huber would also down-weight tails but still tracks the mean below the threshold; the user explicitly wants median-targeting.
F.0.2.7Exercise 2.7 and Exercise 2.8 (statements: p. , p. ).¶
These are coding exercises (notebook lecture_03_02_Brock_Mirman_Uncertainty_DEQN.ipynb); reference outputs and timing curves are in the companion repository. Qualitative anchors: in Ex. Exercise 2.7, the per-epoch wall time of tensor-product Gauss--Hermite ( nodes) should grow exponentially in while Stroud-3 ( nodes) grows linearly, with a crossover that is visible already at --5 on a single GPU; the relative Euler error should track the integration accuracy of each rule, with Stroud-3 inheriting the fourth-moment bias of Section 2.6.3. In Ex. Exercise 2.8, swapping Swish for typically slows time-to-converge by tens of percent on a smooth problem like Brock--Mirman because saturates faster, but final accuracy is comparable; convergence should still hold under the same hyperparameters.
F.0.3Chapter Chapter 3: The International Real Business Cycle Model¶
F.0.3.1Exercise 3.1: Fischer--Burmeister.¶
For the forward direction, suppose , , . Without loss of generality ; then since . By symmetry the same holds when .
For the reverse direction, suppose , i.e. . The right-hand side is non-negative, so . Squaring: . Combined with and , the only possibility is one of being zero and the other non-negative, i.e. and .
The level set is the union of the non-negative -axis and the non-negative -axis (an L-shape in the plane). The smoothed variant rounds the corner at the origin: at one finds , while far from the origin and the smoothed level set converges to the unsmoothed L-shape. In a numerical setting the smoothing eliminates the gradient kink at the origin, which is convenient for AD but distorts the strict KKT zero set by an amount.
(c) Gradient direction. At an interior point of the open positive quadrant, . At this evaluates to , both components strictly positive. The raw gradient therefore points northeast, away from the L-shaped zero set, so the bare residual on its own is not the right object for SGD to descend on. What does descend toward the zero set is the squared loss : by the chain rule , and inside the open positive quadrant , so has both components strictly negative at and points southwest, i.e. back toward the closer feasible axis. This is the operative observation for training: SGD on is what pulls infeasible iterates back to the L; the raw gradient on its own would push them away.
(d) Sign convention. Replacing by leaves the squared loss untouched: , so the gradient field of the loss and the SGD trajectory are unchanged. In particular, the sign convention versus is irrelevant once the residual is squared, and the operative quantity for SGD is rather than . The L-shaped zero set is invariant under sign flip; only the value of at off-zero points changes (it flips sign), and squaring removes that distinction.
F.0.3.2Exercise 3.2: State-space scaling.¶
For an IRBC with symmetric countries, the state vector contains for a total of components. The network outputs the next-period capital vector , the irreversibility multipliers , and the resource-constraint shadow price , for outputs in total. Country-level consumption is recovered algebraically from via the consumption-sharing FOC and is therefore not a separate output. The loss has Euler residuals, Fischer--Burmeister residuals from the irreversibility complementarity, and 1 aggregate-resource-constraint residual, components total, matching the outputs. Each Euler residual is an expectation over a -dimensional shock vector (one country-specific innovation plus one aggregate, as in equation (3.4)).
Tensor-product Gauss--Hermite at costs evaluations per residual. Setting gives , so already exceeds the threshold, and overshoots by a factor of nearly 6 (cost ).
The Stroud-3 rule has nodes per residual. Setting gives , comfortable for any IRBC dimension actually used in practice. At the monomial cost is 102 nodes; the tensor cost is evaluations. This four-order-of-magnitude gap at and twenty-order-of-magnitude gap at is the operational reason DEQNs use Stroud-3 by default once .
F.0.3.3Exercise 3.3: Two-phase training.¶
At a randomly initialized network, the policy outputs are not coordinated with the resource constraint. Suppose the network produces values that, summed and combined with country- consumption, exceed total output: . The implied state on the next simulated step has for some country (irreversibility violated), or (negative consumption), or both. Concretely, take , , , , and a random network output (instead of the symmetric steady state). Capital has dropped by in one step, so , violating irreversibility. Even before the irreversibility check fires, the implied consumption becomes huge, and in the next step the marginal utility is essentially zero, so the Euler residual gradient is uninformative.
Phase 1 (uniform sampling on a wide box of states, with Euler residuals computed against any feasible policy guess) gives the optimizer signal to bring outputs into the feasible region before any simulation is attempted. Once the policy is in a feasible neighbourhood, Phase 2 (simulation-based sampling on the ergodic set) refines accuracy. Without Phase 1, the simulation in Phase 2 starts in regions where the policy is grossly infeasible, the loss explodes, and gradient descent diverges.
F.0.3.4Exercise 3.4: Adjustment-cost partials and Tobin’s Q.¶
Write . Then . The partials are
matching equation (3.6).
At the steady state, so . Both partials vanish: and . The adjustment cost itself , and its first-order presence in the resource constraint and the Euler equation drops out. The deterministic steady state of the IRBC with adjustment costs is therefore identical to the frictionless steady state, being pinned down by .
The expression is the marginal cost of investing one more unit and is the IRBC’s analogue of Tobin’s marginal Q: large positive (rapid expansion) creates a large investment wedge, raising the effective per-unit cost of capital next period. Higher flattens the response of investment to a productivity shock: a large adjustment cost makes the planner spread the response of across several periods rather than absorbing the shock in one big move, slowing convergence to the new steady state. In the limit , capital adjusts only infinitesimally each period and the dynamics become arbitrarily slow.
F.0.3.5Exercise 3.5: Complete-markets risk sharing.¶
The consumption-sharing condition (3.12) reads . Therefore
(i) With homogeneous IES , the exponent vanishes and the ratio collapses to a time-invariant constant:
Since is constant, , the perfect risk-sharing prediction of Backus et al. (1992): cross-country consumption growth is perfectly correlated (correlation ).
(ii) With heterogeneous IES , the exponent is non-zero and enters the ratio. As shocks move the planner’s shadow price, the consumption ratio fluctuates: low-IES countries’ consumption is less sensitive to than high-IES countries’. But the log growth rate is still
Thus, for positive , any pair of country consumption-growth rates is a positive scalar multiple of the same aggregate shock . The correlation remains one; heterogeneous IES changes relative consumption-growth volatility, not the correlation, in this complete-markets planner allocation.
(iii) The empirical consumption-correlation puzzle is that real-world cross-country consumption growth correlations sit well below the near-perfect correlations implied by the complete-markets benchmark. Heterogeneous IES alone does not break the common-shadow-price structure; closing the gap with the data requires incomplete markets, wedges, nontraded goods, preference nonseparabilities, or other frictions that break full insurance.
F.0.3.6Exercise 3.6 and Exercise 3.7 (statements: p. , p. ).¶
These are notebook exercises (lecture_05_05_IRBC_Exercise.ipynb); reference solutions are in the notebook itself, behind the “attempt first” dividers. Qualitative anchors: in Ex. Exercise 3.6, the closed-form steady state falls in all three scenarios --- a higher raises the required net return , a lower raises , and a lower shrinks the multiplicative term while (since ) steepening diminishing returns --- so is decreasing in , increasing in , and increasing in around the baseline, with following by substitution. In Ex. Exercise 3.7, inverse-loss weighting equalizes the per-component contributions , so the smallest-magnitude residuals (here the Fischer--Burmeister terms) receive the largest weight; the speed-up is largest when a component is small because it is hard to fit, and the scheme can hurt when a component is small because it is already satisfied by construction (e.g., a hard-coded resource constraint), in which case up-weighting it merely amplifies noise.
F.0.4Chapter Chapter 4: Neural Architecture Search and Loss Normalization¶
F.0.4.1Exercise 4.1: Random vs. grid.¶
With two hyperparameters and only one “important” axis, a grid uses 9 candidates but only 3 distinct values along the important axis. If the near-optimal interval has length fraction and its location relative to the grid is unknown, the grid hit probability is approximately when is small. Random search at 9 evaluations samples 9 independent values along the important axis, so its hit probability is
For , the grid probability is approximately 0.15, while random search gives .
The general principle: with evaluations and only important axes, random search effectively gives independent draws on those axes (since the irrelevant axes don’t matter), while grid search wastes most of its budget on the irrelevant axes’ marginals. This is the projection argument of Bergstra & Bengio (2012): when the loss landscape is anisotropic, random search dominates grid search.
F.0.4.2Exercise 4.2: Bayesian optimization toy problem.¶
This is a coding exercise. A grid with step size 0.01 over has 301 points, so the qualitative benchmark is that BO should require far fewer objective evaluations when the GP posterior and acquisition function identify the promising region early. The exact evaluation count is a notebook output and depends on the initial design, acquisition optimizer, random seed, and stopping rule.
F.0.4.3Exercise 4.3: Hyperband budget allocation.¶
Hyperband with , runs a ladder of brackets indexed by , where . Each bracket starts with candidates trained for resource each, then runs Successive Halving with reduction factor . Table Table F.2 works out the resulting schedule.
Table F.2:Hyperband schedule for maximum resource and reduction factor . Each row reports the successive-halving rungs inside one bracket and the total resource consumed by that bracket.
| SHA rungs | Total | |
|---|---|---|
| 4 | 405 | |
| 3 | 363 | |
| 2 | 351 | |
| 1 | 378 | |
| 0 | 405 |
Within each bracket, Successive Halving reduces candidates by at each rung and increases the resource per surviving candidate by . Therefore the total cost must sum all rungs, not only the first rung. With the floor/ceil schedule above, total Hyperband budget is
resource units, just below the loose worst-case bound .
A naive “train all candidates to full ” costs resource units. Hyperband is only moderately cheaper in total resource here, but it screens a much larger initial pool: across the five brackets, the total number of first-rung candidates is , vs. 27 for the naive scheme. Its advantage is adaptive allocation: many more candidates are sampled, but only a small subset receives large training budgets.
F.0.4.4Exercise 4.4: Loss balancing.¶
Let have magnitude and per-component gradient norm . If we crudely model gradient norm as scaling linearly with loss magnitude (true for, e.g., quadratic losses far from the optimum), then . Equalising gradient contributions requires , i.e. , which after normalisation becomes
The scheme breaks down when the gradients are correlated: means that scaling up to “boost” also moves along the direction, changing . The “equal contribution” targeted by the fixed weights is no longer a fixed point: each parameter update changes the local gradient geometry, and weights tuned at one iteration become wrong at the next. Adaptive schemes (ReLoBRaLo, GradNorm) re-tune the at every step, recovering the equalisation in a way that fixed weights cannot.
F.0.4.5Exercise 4.5: Pareto frontier geometry.¶
(i) Differentiate in and set to zero: , hence
(ii) Substituting back:
(iii) Take square roots: and . Adding:
independent of . This is a convex curve in space (a quarter of an astroid-like arc) running from at to at .
(iv) At , , the midpoint, and . This sits on the symmetric axis of the front.
(v) In the one-dimensional toy problem the trade-off is completely described by the curve above. In a neural network, however, is high-dimensional and the descent direction for fixed scalar weight is
If , reducing one component tends to reduce the other; if the inner product is negative, progress on one component can increase the other. Because this geometry changes along the training path, a fixed scalar weight can balance progress at one iterate and become badly unbalanced later. ReLoBRaLo responds to this by increasing the weight of losses whose relative loss progress has lagged behind. GradNorm is the related method that targets gradient magnitudes directly by trying to balance across components.
F.0.4.6Exercise 4.6: ReLoBRaLo vs. GradNorm.¶
This is a coding exercise. Qualitatively: GradNorm requires one extra backward pass per component per step (to compute ), so wall-clock per epoch is roughly slower than ReLoBRaLo for components. In return, GradNorm achieves tighter gradient balance, which matters when component magnitudes are not a faithful proxy for gradient magnitudes (e.g., when the loss landscape is anisotropic). For the standard PINN losses studied in this script ( or 3 components, typically scaled by physical units), ReLoBRaLo’s loss-magnitude proxy is usually good enough and the extra cost of GradNorm is not warranted; for losses with strongly heterogeneous Hessians (e.g., HJB residuals coupled with KFE residuals where the two operators have different stiffness), GradNorm’s direct gradient measurement can give a meaningful speedup.
F.0.4.7Exercise 4.7: HPO vs. full NAS decision.¶
Sketch. The four cells are roughly:
(a, i) RTX 3060 + fixed-topology MLP search: Random Search with Successive Halving. Search space is small (a few thousand candidate combinations), the GPU is too small for graph-level NAS, and SH amortizes the budget across many candidates by killing weak ones early. Bayesian Optimization helps marginally but adds GP-fitting overhead that is not worth it on a single GPU.
(a, ii) RTX 3060 + graph-level NAS: Random Search. Full DARTS-style NAS would not fit in 12 GB of VRAM (the supernetwork concept-search needs several model copies in memory simultaneously); a small fixed pool of architectures evaluated at low resource is the only feasible option.
(b, i) A100 + fixed-topology MLP search: Bayesian Optimization. The A100’s compute headroom makes the per-step BO overhead negligible, and the search space’s smooth landscape (continuous learning rate, ordinal depth/width) is exactly where GP surrogates dominate Random Search.
(b, ii) A100 + graph-level NAS: Full graph-level NAS (DARTS or evolutionary). The A100’s memory and compute support the supernetwork training that DARTS requires; the search space has too many discrete connectivity choices for any HPO method to cover.
The general rule: budget grows smarter methods become affordable; search-space size grows the marginal benefit of smarter methods grows; per-method overhead per evaluation needs to fit inside one GPU step or it eats into the budget itself.
F.0.5Chapter Chapter 5: Overlapping Generations Models with DEQNs¶
F.0.5.1Exercise 5.1: OLG market clearing for .¶
With three cohorts (young , middle , old ), the budget constraints are
where are equilibrium prices and are exogenous lifecycle labor endowments (the old cohort consumes its capital). Two Euler equations determine the savings of the young and middle cohorts:
The market-clearing condition closes the system:
where is aggregate capital.
Equation count: three budget constraints (used to eliminate consumption), two Euler equations, one capital-market-clearing identity. The budget constraints are bookkeeping, so the network outputs the two cohort savings and is trained on the two Euler residuals; aggregate capital then determines next-period prices algebraically through the firm FOCs. The unknown count (two savings) matches the Euler-residual count (two), and the market-clearing identity is built into the definition of .
F.0.5.2Exercise 5.2: KKT under FB.¶
For agent with borrowing constraint and Lagrange multiplier , the KKT system is
These three conditions are encoded by the single Fischer--Burmeister equation with . The Euler equation
contributes a second residual. Squared and summed:
At any KKT point, both squared terms vanish exactly: the Euler residual is zero by definition, and encodes complementarity. This is what “vanishes exactly at the KKT point” means: there is no smoothing or penalty parameter, the loss is zero on the equilibrium and strictly positive off it. Compare with a quadratic penalty : this also vanishes at the KKT point but the multiplier has to be tuned, whereas FB has no parameter.
F.0.5.3Exercise 5.3: Hump-shaped lifecycle.¶
A hump-shaped labor-income profile peaks at middle age and declines toward retirement. The lifecycle savings policy inherits this hump for two reasons. (i) Consumption smoothing: agents with high current income relative to lifetime average save heavily to fund retirement years when drops. (ii) Time-varying borrowing constraint: young agents have low income, want to borrow against future earnings, are constrained by , so they save little; middle-aged agents are unconstrained and save the most; old agents dis-save toward death.
The expected shape: for the very young (constrained), peaks around age 40--50 (middle of working life), declines toward retirement, drops to zero for the oldest cohort that does not save into the next period. In notebook lecture_08_10_OLG_Benchmark_DEQN_persistent.ipynb, plotting the trained network’s against cohort age should reveal exactly this single-peak shape; the position of the peak depends on the calibration of and on the lifecycle labor profile.
F.0.5.4Exercise 5.4: Hard aggregation layer.¶
Coding exercise. The current analytic notebook already clears the capital market by defining as the sum of predicted cohort savings. The alternative hard-layer variant is useful when the network has a separate aggregate-capital head. Implementation sketch: output a positive scalar and unnormalised cohort scores ; apply softmax along the cohort axis, ; rescale to capital:
The market-clearing residual is identically zero up to floating-point precision. The comparison with the current notebook should therefore focus on Euler residuals and wall-clock time: the hard layer removes one possible inconsistency but also changes the parameterisation, so faster convergence is an empirical question rather than a mathematical guarantee. In multi-asset settings each exact clearing condition needs its own accounting layer, which is why the 56-agent benchmark enforces bond-market clearing as an explicit residual instead.
F.0.5.5Exercise 5.5: Bond pricing in equilibrium.¶
Cohort ’s Euler equation for capital is
and for the riskless bond that costs today and pays one unit of consumption next period,
The second equation gives directly
Identifying the stochastic discount factor , the same expression reads .
For the risk-premium decomposition, divide the capital Euler by and use the covariance identity :
Substituting :
which after rearrangement gives the textbook risk-premium decomposition: the gap between expected gross capital return and the riskless rate equals minus the SDF--return covariance, scaled by .
When the collateral constraint binds. If the collateral constraint is active, with non-negative KKT multiplier entering the bond FOC with coefficient (the same that controls the constraint ), the bond Euler equation becomes
so the equilibrium bond price is
The unconstrained SDF expression is recovered when . The multiplier wedge raises , equivalently lowers the implicit safe rate that tracks, because the constrained agent values one extra unit of bond consumption tomorrow more than the unconstrained agent. In the 56-agent benchmark, the cohorts most likely to bind are the youngest (lowest income, highest desire to borrow against future earnings), so any wedge from the binding-cohort population enters the cross-sectional pricing equation.
Why no bond residual in 6-agent OLG? In the analytic 6-agent calibration there is only one asset (capital). Bonds are absent, so no separate market-clearing residual is needed. The single-asset Euler equation pins down the implicit safe rate via minus the appropriate covariance, but no quantity needs to clear because no bond is traded.
F.0.5.6Exercise 5.6 and Exercise 5.7 (statements: p. , p. ).¶
Coding exercises. Both call for 4--5 retraining runs of the 56-agent benchmark and a binding-frequency / steady-state diagnostic. The binding indicator should be based on small slack and a positive multiplier, not on a large complementarity residual: at a well-trained KKT solution the product residual is close to zero both when a constraint binds and when it is slack. Expect borrowing and collateral constraints to bind mostly for young cohorts; as rises, the lower bound becomes tighter, so negative bond positions should shrink and cross-cohort bond dispersion should typically fall. The equilibrium price response is a general-equilibrium object and should be read from the retrained models rather than imposed analytically.
F.0.6Chapter Chapter 6: Heterogeneous Agents and Young’s Method¶
F.0.6.1Exercise 6.1: Mean-preserving lottery.¶
Place mass at and at . Mean preservation:
Solving for :
This is well-defined for since the denominator is positive and the numerator lies in , ensuring .
Mass conservation: the two probabilities sum to one, , so total mass is preserved exactly under this redistribution. Equivalently, the weight is the unique linear interpolation weight that makes the discrete two-point distribution have mean , which is what defines Young’s redistribution operator on a fixed grid.
Higher-moment matching is impossible with a two-point split unless coincides with a grid point: any non-degenerate two-point distribution with mean and support has variance , while the original (delta) distribution at has zero variance. This residual variance is the price of the discretization, and it shrinks as the grid is refined.
F.0.6.2Exercise 6.2: Closed-form bracketing on log-spaced grids.¶
Coding exercise. Algorithm sketch: with grid , the bracket index for a query is
This is per query (one log + one floor), independent of grid size . By contrast, numpy.searchsorted costs per query (binary search). The speed difference is hardware- and implementation-dependent, so the coding exercise should report the measured wall-clock ratio on the vectorized batch rather than treating a fixed multiplier as universal.
F.0.6.3Exercise 6.3: Approximate aggregation, scope.¶
The KS log-linear rule is built on the empirical observation that mean capital alone is a sufficient statistic for forecasting in the standard Aiyagari--Krusell--Smith calibration. This approximate aggregation breaks when the cross-sectional distribution carries information beyond its first moment that materially affects equilibrium prices.
Counterexample 1: multiple assets with switching liquidity. Add a second asset (say a corporate bond) with state-dependent liquidity: in good times agents trade both assets freely; in bad times the bond becomes illiquid. Now the share of wealth held in the bond, plus the bond--capital correlation in the cross-section, both determine prices, and neither can be summarized by mean capital alone.
Counterexample 2: heterogeneous discount factors. If agents differ in and the cross-sectional distribution of is dynamic (e.g., new entrants have different ), then mean capital understates the dispersion, and the equilibrium interest rate depends on which subpopulation holds the marginal unit of capital.
Why higher moments do not always rescue. Adding the variance to the forecasting rule helps with smooth perturbations but cannot capture multi-modal distributions, regime-switching, or non-monotone responses to skewness. The fundamental issue is that the master equation requires full cross-sectional information whenever prices are non-linear in the distribution; truncating to any finite set of moments is exact only in the linear-pricing case.
F.0.6.4Exercise 6.4: Sequence-space vs. histogram DEQN.¶
Coding exercise. Empirically: with truncation horizon and the chapter’s reference calibration, the sequence-space residual after training matches the histogram-based DEQN to within a factor of 1.2--1.5 on the same model. The sequence-space variant generalizes worse to a much longer test horizon () because the truncation error grows with the gap; the histogram variant does not have this issue because its state is stationary. The trade-off favors sequence-space when the cross-sectional distribution is intrinsically high-dimensional (e.g., multiple assets, multi-cohort wealth), at which point storing shock realizations is cheaper than discretizing the distribution.
F.0.6.5Exercise 6.5: DeepSets permutation invariance.¶
(i) Let be a permutation of . The aggregator’s -th component is
where the second equality is just a re-indexing of the sum (since addition is commutative). Therefore , exactly invariant.
(ii) The policy is a function of agent ’s own state , the population summary , and the aggregate exogenous state . Under a permutation , agent 's individual state is now , while and are unchanged (by the result in (i) for ). Therefore the policy of agent in the permuted economy equals the policy of agent in the original economy, i.e. the policy moves with its own agent index but is otherwise unaffected: equivariance.
(iii) Zaheer et al. (2017) prove that any continuous permutation-invariant function on sets of fixed cardinality can be written as for some continuous functions . This is the universal-approximation result for permutation-invariant DeepSets.
Implication for DeepHAM. Since the equilibrium price functional is permutation-invariant in agents (anonymous markets), DeepHAM’s parameterization can in principle approximate any continuous price/policy functional of the cross-sectional distribution to arbitrary accuracy, provided the inner network has enough capacity and the moment vector is rich enough. The number of moments plays the role of the encoder’s bottleneck dimension: empirically, --3 suffices for Krusell--Smith-class economies, consistent with the chapter’s report that DeepHAM with one learned moment matches the histogram DEQN.
F.0.6.6Exercise 6.6 and Exercise 6.7 (statements: p. , p. ).¶
Coding exercises. Guidance for interpreting the outputs:
Exercise 6.6. The relevant statistic is the cross-replication sampling variance conditional on the same aggregate path, not the time-series variance of along that path. As rises, the Monte Carlo standard error should fall at the usual rate for smooth aggregate statistics. Young’s path has zero sampling variance across replications because the histogram update integrates out the lottery exactly. The MC-vs-Young trade-off depends on the target functional: tail mass (e.g., the bottom- wealth share) decays much more slowly under MC, so the panel size needed to match Young-equivalent precision is an output of the repeated-panel experiment.
Exercise 6.7. In the standard KS calibration, the one-moment forecasting rule should already fit extremely well; adding , with , is expected to give only a small incremental gain. This is exactly the empirical observation behind “approximate aggregation”. In calibrations with high cross-sectional dispersion (e.g., wide income range or frequent borrowing-constraint binding), the second-moment improvement can become economically visible and should be reported from the run.
F.0.7Chapter Chapter 7: Physics-Informed Neural Networks¶
F.0.7.1Exercise 7.1: Trial-function BC enforcement.¶
Define . Evaluate at the boundaries:
Both boundary conditions hold for any network output , so the BCs are encoded in the architecture rather than enforced via the loss.
Why preferable to a soft penalty? A soft penalty in the loss involves a hyperparameter that must be tuned: too small, and the BC violation is large; too large, and the interior PDE residual is starved of optimization budget. The trial-function enforcement is parameter-free, makes the BC residual identically zero, and reduces the loss to the single PDE-interior term . This separates the two optimization concerns cleanly; any wall-clock gain should be measured in the notebook rather than assumed.
F.0.7.2Exercise 7.2: ReLU pathology.¶
A ReLU network is piecewise-linear: between consecutive kinks it is affine in , so a.e. At a kink, the second distributional derivative is a Dirac delta supported on a measure-zero set. The strong-form Black--Scholes residual
must hold pointwise for almost every . With ReLU, a.e., so the residual reduces to , which has no nontrivial solution that respects the option-pricing boundary condition. The PINN cannot decrease its loss below the order of magnitude of the missing term.
Weak-form fix. Multiply both sides by a smooth test function with compact support on and integrate by parts on the term:
The boundary terms vanish for compactly supported , and the residual now involves only first-order derivatives of . ReLU networks have well-defined first derivatives a.e., so the weak-form PINN can minimize this residual. This is exactly the Galerkin / Deep Galerkin formulation of Sirignano & Spiliopoulos (2018).
F.0.7.3Exercise 7.3: Discrete continuous bridge.¶
Start with
Then . The same first-order limit follows from the implicit-Euler convention .
Taylor-expand around :
Substitute and use :
Subtract from both sides and divide by :
Take and rearrange:
This is the HJB equation for the consumption-savings problem with no asset return (or with embedded into , in which case the HJB picks up an additional drift term). The discrete-to-continuous bridge thus shows that the HJB is the formal limit of the discrete Bellman as the time step shrinks, which justifies treating PINNs as the continuous-time analogue of value-function iteration.
F.0.7.4Exercise 7.4, Exercise 7.5, Exercise 7.6 (statements: p. , p. , p. ).¶
Coding exercises. The exact numbers below depend on random seeds, batch sizes, and stopping rules; use them as qualitative checks rather than fixed targets:
Exercise 7.4. At small , the BC residual is underweighted and endpoint violations remain visibly large. At very large , the endpoints fit well but the interior residual can stagnate because the optimizer spends most of its gradient budget on the boundary term. The elbow is the smallest for which further increases mostly improve the boundary metric without improving the interior fit. The hard-BC variant should be the benchmark: it sets the boundary violation to numerical zero by construction and removes the penalty-weight tuning problem.
Exercise 7.5. Sobol and Latin Hypercube points usually reduce visible sampling gaps relative to uniform random points. On the smooth manufactured Poisson problem the gain may be modest, because the solution has no boundary layer or interior singularity. Adaptive sampling becomes more valuable when residuals are spatially localized; report the actual collocation count, wall time, and test-grid residual rather than relying on a universal percentage saving.
Exercise 7.6. The expected qualitative result is that the strong-form PINN is the natural baseline for Black--Scholes, because is well-defined by automatic differentiation. A strong-form ReLU network is ill-suited because almost everywhere and undefined at kinks. In a weak formulation, integration by parts moves the second derivative off the network and onto the test function, so a ReLU network can be made mathematically admissible. Any empirical comparison should report held-out pricing errors and residual diagnostics from the implemented notebook rather than quoting architecture-independent iteration counts.
F.0.7.5Exercise 7.7: Operator learning vs. PINN.¶
Eleven independent PINN runs each cost wall-clock seconds, total . A single operator-learning or parametric-PINN run trained on 11 values of (or a continuous range, sampled in mini-batches) costs . Amortized training wins when , i.e., . The crossover scales linearly in the number of distinct values: with strikes, operator learning wins whenever . This is the cost-amortization argument that motivates DeepONet-style operator learning Lu et al., 2021.
F.0.8Chapter Chapter 8: Heterogeneous Agent Models in Continuous Time¶
F.0.8.1Exercise 8.1: Itô on GBM.¶
Geometric Brownian motion satisfies . Apply Itô’s lemma to with , :
Simplifying:
Integrating from 0 to :
Volatility drag. Taking expectations: , but . The expected log return is strictly less than the log of the expected return, , by the variance correction term. This is the volatility drag. Two illustrative regimes: with zero arithmetic drift (), expected log growth is , strictly negative; with drift exactly equal to the Itô correction (), expected log growth is zero (the drift just offsets the drag). In financial terms, volatility eats into geometric returns; this is why an asset with expected return and volatility delivers a long-run geometric mean of only .
F.0.8.2Exercise 8.2: KFE for an OU process.¶
The OU process has drift and diffusion coefficient . The KFE in conservation form is
Setting for the stationary density :
Integrate once in , with the constant of integration set to zero by the no-flux boundary condition at :
This is a linear ODE for ; integrating gives , i.e.
This is a Gaussian density with mean and variance , normalised by :
The OU’s stationary distribution is Gaussian with mean equal to the mean-reversion target, variance equal to the diffusion-to-mean-reversion ratio : faster mean reversion (larger ) shrinks the dispersion; larger diffusion grows it.
F.0.8.3Exercise 8.3: Functional derivative.¶
For the master-equation toy specification where is fixed (does not depend on ), the functional derivative measures the linear response of to a perturbation in .
In the ambient vector space of signed measures, a point perturbation gives , where is a Dirac mass at . Substituting,
Therefore . If we restrict to the probability simplex, perturbations must preserve total mass; for example, gives directional derivative . Equivalently, on the simplex the derivative kernel is identified only up to an additive constant.
Interpretation. The functional derivative at a point is the value contribution of an infinitesimal mass placed at . In the toy spec where is just a population average of utilities, the contribution is the per-agent utility at that point. In the real master equation, would itself depend on (because prices depend on ), and the functional derivative would pick up additional indirect terms via ; this is what makes the master equation a genuinely infinite-dimensional PDE rather than a parametric family of finite PDEs.
F.0.8.4Exercise 8.4: HJB residual.¶
Coding exercise. The right answer is the out-of-sample residual table produced by your run of lecture_13_08_Aiyagari_Continuous_Time_FD_and_PINN_PyTorch.ipynb. Report the training budget, collocation batch, random seed, and test grid. The residual should decrease when the collocation budget and network capacity are increased, but the scaling is empirical rather than a universal law because it mixes approximation, optimization, and sampling error.
F.0.8.5Exercise 8.5: Closed Aiyagari system.¶
Combining the four ingredients:
HJB (from (8.11)):
KFE for the stationary distribution (from (8.6), with ):
where is the optimal savings function.
Firm FOCs (Cobb--Douglas):
Market clearing:
The equilibrium objects are , with often pinned down by the stationary income shares and implied by the firm FOCs once is known. In practice one fixes a candidate , computes the associated firm demand and wage, solves the HJB for and hence the policy , plugs into the KFE for , computes implied , and compares this capital supply with the capital demand implied by the candidate . A fixed point in is the equilibrium. This is the bisection-on- algorithm of Achdou et al. (2022), and the PINN replaces the inner HJB and KFE solves with neural-network approximation while keeping the outer fixed-point loop on unless the full equilibrium system is learned jointly.
Why both must be solved consistently at each candidate . The HJB takes as an input (price-taking agents); the KFE takes the policy from the HJB. Mis-specifying during training would feed a mis-specified policy into the KFE and yield an inconsistent . In the production-scale solver, the fixed-point loop alternates HJB and KFE to convergence at each before updating ; the PINN can be trained on all four equations jointly when the architecture is rich enough to learn the equilibrium price as an output.
F.0.8.6Exercise 8.6 and Exercise 8.7 (statements: p. , p. ).¶
Coding exercises. Expected diagnostics:
Exercise 8.6. With a fixed policy, the finite-dimensional KFE is a linear forward equation. If the discretized generator is ergodic, the distance to the stationary distribution should decay approximately exponentially after transient modes die out. Estimate the slope from your run rather than quoting a universal number; the fitted rate is controlled by the slowest nonzero eigenvalue of the KFE generator and depends on income-switching intensities, savings drift, and grid truncation.
Exercise 8.7. On the one-asset stationary benchmark, finite differences should usually win on absolute wall-clock time and give the cleanest low-dimensional benchmark residuals. A PINN may become more attractive when the same architecture is reused across many nearby parameter values, when warm starts work well, or when the state space is extended beyond what a grid handles comfortably. Report the actual cold-start and warm-start timings from your machine, and treat memory use as hardware- and backend-dependent.
F.0.9Chapter Chapter 9: Gaussian Processes¶
F.0.9.1Exercise 9.1: Posterior on three points.¶
The RBF kernel with length scale and signal variance is . With training points and targets , the kernel matrix is
Adding observation noise to the diagonal of and solving with by Gaussian elimination gives
At ,
Posterior mean:
For the variance, solve , giving , hence
The posterior is , with standard deviation . Notice the posterior mean “smooths” the two flanking observations and rather than being pulled to either; the 0.158 standard deviation reflects partial information at a halfway point between two data points.
F.0.9.2Exercise 9.2: Marginal likelihood Occam.¶
The log marginal likelihood is
where is the kernel matrix at length scale . The first term penalizes misfit (data that don’t lie in the GP’s predicted manifold get a high ); the second term penalizes model complexity ( is large when the kernel can fit anything, small when it is rigid). This is the Bayesian Occam’s razor: small gives a flexible model that fits any training data perfectly (small misfit) but accepts a large complexity penalty; large enforces smoothness (large misfit if the data are not smooth) but enjoys a small complexity penalty. The optimum balances the two.
For three data points at , plotting against typically shows an interior maximum near the data’s natural variation scale. At , the kernel is very local: each point is nearly uncorrelated with its neighbors, so the data fit is easy but the flexible prior receives a complexity penalty. At , the kernel forces all three function values to be nearly equal, which fits the data poorly. The peak is the point where these two forces balance.
F.0.9.3Exercise 9.3: Active subspace by hand.¶
For on , the gradient is
The dominant term is along (with weight roughly ), and the perturbation along is two orders of magnitude smaller.
Compute with i.i.d., so . Let ; then , , and . Substituting,
where and the correction comes from the perturbation. Since has eigenvalues (eigenvector for the nonzero one), the leading eigenvalue of is , with eigenvector , the “aggregate direction.” The next eigenvalue is , four orders of magnitude smaller. The active subspace of dimension 1 already captures essentially all of the function’s variability.
F.0.9.4Exercise 9.4: Deep vs. linear active subspace.¶
Coding exercise. The linear-AS diagnostic should show two nonzero eigenvalues for the radial-ridge target, with the remaining eigenvalues close to numerical zero. Thus a linear active subspace needs to represent the two linear features and . Deep AS can reach its validation-MSE elbow already at because the encoder can learn a scalar nonlinear aggregate such as . Report the held-out MSE curve and eigenvalues from the run rather than quoting universal numbers, since optimization noise and train/validation splits move the exact diagnostics.
F.0.9.5Exercise 9.5: BAL on a 2D function.¶
Coding exercise. Pure-variance acquisition selects points purely by where the GP is most uncertain, ignoring the predicted mean. The resulting design is usually more uniform across the input domain because the GP variance is high wherever data is sparse, regardless of function value. Maximizing pure gives exactly the same design as maximizing pure , since the logarithm is monotone. Differences arise only once the acquisition is mixed with a mean term, for example : then the design tilts toward regions that are both uncertain and high-valued under the current surrogate. For global surrogate construction, pure variance is the cleaner baseline; for optimization-like goals, the mixed score may be useful.
F.0.9.6Exercise 9.6: Sobol sensitivity with a GP surrogate.¶
Coding exercise. Report the actual errors from the run rather than treating fixed percentages as universal reference outputs. The expected pattern is improvement as increases: first-order Sobol errors should fall from small to larger sample budgets, while total-effect indices may converge more slowly because they include interaction terms. The cost ratio is the important lesson: once the surrogate is trained, very large Sobol designs can be evaluated at negligible marginal cost relative to repeated true-model solves, which is why surrogate-based sensitivity analysis is standard for expensive simulators such as climate IAMs.
F.0.9.7Exercise 9.7: Prior-driven RBF-GP extrapolation outside the training domain.¶
(i) Coding: on the training interval the GP closely tracks with credible band of width .
(ii) Analytical claim: for an RBF kernel , when for all training points , the kernel cross-vector . Therefore the posterior mean (the prior mean). The posterior variance is
the prior variance. Hence far from data the GP literally returns the prior , regardless of the training data.
(iii) Coding verification: at (with for the training data), the cross-kernel is , well below floating-point precision. Posterior mean , posterior s.d. (whatever was learned via marginal-likelihood maximisation).
(iv) The implication is more subtle than “overconfidence.” Far from the training data the posterior literally reverts to the prior, so the band there is exactly what the prior would have produced before any data were observed; it is overconfident only when the prior variance or the learned length scale is itself misleading, for instance when was calibrated by marginal-likelihood maximization on a training set that does not represent the function’s scale outside the training hull. In particular, the posterior does not know that continues oscillating outside ; it just reverts to zero with a band of width , regardless of whether the true function actually stays close to zero there. Bayesian active learning algorithms that select points by maximum posterior variance can therefore fail to acquire informative samples outside the convex hull when the prior variance is no larger than the within-hull noise scale.
Mitigations: use a Matérn kernel with or (heavier-tailed than RBF, posterior reverts to prior more slowly), incorporate a polynomial mean function in the GP prior (so extrapolation grows with instead of decaying to zero), or use a boundary-aware acquisition function that explicitly penalizes exploitation outside the convex hull. In economic applications (e.g., extrapolating an estimated value function to wealth levels outside the training range), the safest practice is to flag any query outside the convex hull of training data and refuse to predict, rather than to trust a prior-driven band that has no data behind it.
F.0.10Chapter Chapter 10: Deep Surrogate Models and Structural Estimation¶
F.0.10.1Exercise 10.1: Identification.¶
F.1Let be the simulated moment vector implied by the persistence parameter. At the truth , local identification is captured by the Jacobian $$M(\varrho^\star)¶
\frac{\partial m(\varrho)}{\partial \varrho}\bigg|_{\varrho^\star}.$|M_k(\varrho^\star)|\varrho$ produce nearly invisible changes in the moment and the SMM objective becomes flat.
Brock--Mirman example. The output autocorrelation is typically the strongest local moment for , because it is a direct echo of the productivity AR(1). The autocorrelation of consumption growth is also informative, but more filtered through equilibrium dynamics. The mean savings rate is nearly flat in the scalar exercise and is therefore weakly identifying for persistence. The exact ranking should be reported from the finite-difference Jacobian in the notebook, not from a hard-coded number.
F.1.0.1Exercise 10.2: Optimal weighting.¶
F.2The SMM objective is , where is the moment-error vector. Under standard regularity (Hansen 1982), the asymptotic variance of is $$\mathrm{Avar}(\hat\theta)¶
(M^\top W M)^{-1}M^\top W\Omega W M(M^\top W M)^{-1},$M=\partial m/\partial\theta’\theta^\star\Omega=\mathrm{Var}(\sqrt{T}\hat g(\theta^\star))$ is the covariance of the data-simulation moment discrepancy.
F.3To minimize over choices of , set up the Lagrangian or use the matrix calculus result that the variance is minimized when . Substituting : $$\mathrm{Avar}(\hat\theta)\big|_{W^\star}¶
(M^\top \Omega^{-1}M)^{-1}.$\Omega=(1+1/S)\Sigma_m\Omega\approx\Sigma_mW=\tilde W\mathrm{Avar}|{\tilde W}-\mathrm{Avar}|{W^\star}$ is positive semi-definite by the Gauss--Markov theorem applied to the moment system.
Why identity weighting in the first stage? The optimal weight depends on the unknown covariance at the truth. The standard two-stage strategy is: (1) estimate with to obtain a consistent but inefficient ; (2) estimate at or near ; (3) re-estimate with .
F.3.0.1Exercise 10.3: Common random numbers.¶
Coding exercise. Without CRN, the objective changes both because changes and because each candidate uses a new shock path. This contaminates the profile with Monte Carlo noise. With CRN, every candidate is evaluated on the same shock path, so differences in isolate the structural effect of persistence. Quantify the gain by repeating the entire candidate grid across Monte Carlo panels and comparing the cross-panel variance of at each grid point.
F.3.0.2Exercise 10.4: SMM vs. SBI.¶
SMM solves an outer optimization at deployment: given new data, run a -step optimization over , where each step requires (a) a model simulation at the candidate and (b) moment computation. Total cost per inference: model evaluations.
SBI (e.g., neural posterior estimation) does the work upfront at training time: simulate the model at values of , train a neural density estimator on the pairs, and then at deployment evaluate on the new data with one forward pass. Total cost per inference (after training): one forward pass.
SBI dominates when (i) the model is expensive but a single training run is amortized over many datasets to be analyzed (e.g., a central bank running daily updates); (ii) the model is non-likelihood (no closed-form likelihood, only simulator); (iii) the parameter dimension is moderate () so training data covers parameter space. SMM dominates when (i) the model is cheap (each evaluation a few ms), (ii) only one or a handful of inferences are needed, (iii) classical confidence intervals are required (SBI gives a Bayesian posterior, which differs).
F.3.0.3Exercise 10.5: -statistic and overidentification.¶
F.4Coding+analytical. In the joint notebook’s over-identified specification, and , so the degrees of freedom are . Under correct specification and with , the -statistic at the optimum follows $$J¶
T,\hat g(\hat\theta)^\top \Omega^{-1}\hat g(\hat\theta) \xrightarrow{d} \chi^2_{2}.$W=\Sigma_m^{-1}$ while simulation noise is non-negligible, adjust the scale under the equal-length independent-simulation approximation or use the Monte Carlo/bootstrap distribution directly.
Empirical distribution: under correct specification, the Monte Carlo distribution of should be centered near the corresponding benchmark once the weighting and simulation-noise treatment are consistent. Under a structural break, the model cannot match all four moments simultaneously, so the distribution should shift to the right and the rejection rate should rise above the nominal size. The size of that shift is an output of the experiment and should be reported from the run.
F.4.0.1Exercise 10.6: Bootstrap confidence intervals.¶
Coding exercise. The nonparametric bootstrap should respect time-series dependence; use a moving-block or stationary bootstrap rather than iid resampling of individual dates. The parametric bootstrap draws new shock paths under the estimated parameter vector and re-runs the estimator. Report the actual CI endpoints and coverage from the run. In small samples, bootstrap intervals may differ materially from sandwich intervals because the SMM criterion is nonlinear and the finite-sample distribution of need not be close to Gaussian.
F.4.0.2Exercise 10.7: ML vs. SMM efficiency.¶
Coding exercise. If is observed and follows
then the Gaussian AR(1) likelihood gives a direct MLE for (OLS of on when is unrestricted). This MLE is efficient for the observed-shock likelihood. The SMM estimator based on a finite moment vector reaches the GMM efficiency bound for those moments, but it equals MLE efficiency only if the chosen moments span the score, which the three pedagogical moments generally do not.
Why SMM despite the efficiency loss? In production-scale models (heterogeneous-agent macro, dynamic IO), the likelihood is often unavailable in closed form, and computing it would require integration over high-dimensional latent states. Moments are cheaper, interpretable, and robust to parts of the model that are not central to the research question. The cost is that SMM efficiency depends on the information content of the chosen moments.
F.4.1Chapter Chapter 11: Climate Economics and Deep Uncertainty Quantification¶
F.4.1.1Exercise 11.1: ECS sensitivity.¶
Coding exercise. Report the SCC at the central calibration and at each ECS value in the likely and very-likely ranges. The expected qualitative pattern is monotone and often convex in ECS: higher equilibrium climate sensitivity raises temperature damages and therefore the emissions shadow price. The quantitative range is calibration-dependent and should be reported from the notebook rather than fixed in the solution text. The interpretation should connect the dispersion to the climate-science finding of Sherwood et al. (2020) that ECS uncertainty is a major driver of SCC uncertainty.
F.4.1.2Exercise 11.2: Sobol decomposition.¶
For with i.i.d.:
Conditional means:
First-order Sobol indices:
Sum: ; the residual is the interaction term.
Total-effect indices (one minus the share explained by all other variables): ; (no interactions involving since it enters only quadratically alone).
A SALib estimate with 104 samples typically matches these analytical values to two decimal places.
F.4.1.3Exercise 11.3: ACE benchmark.¶
Coding exercise. Use ACE’s closed-form optimal carbon tax as the analytic benchmark, then compute the DEQN-trained DICE SCC at the same calibration and report the percentage discrepancy. A small gap is expected only when units, discounting, damage curvature, and time discretization are aligned; any residual difference should be attributed explicitly to the DICE discretization, smoothing choices, and calibration differences rather than to a fixed percentage target.
F.4.1.4Exercise 11.4: Pareto-improving tax design.¶
Project-level coding exercise. The constrained search is over a low-dimensional parameter vector , with the cohort welfare constraints enforced via a penalty or barrier term in the outer optimizer. The Pareto frontier is typically tight: cohorts whose BAU welfare is already close to the unconstrained Ramsey-optimal welfare are easily satisfied, while cohorts that bear the bulk of the transition cost (often the youngest at the time of the reform) bind first; the welfare gap to the unconstrained problem grows with the share of constrained cohorts. Holding fixed at the BAU or declining benchmark leaves measurable welfare on the table because endogenizing the transfer schedule provides an extra free instrument with which to relax the binding constraints. Numerical answers are calibration-dependent and should be reported from the notebook rather than benchmarked against fixed values; the qualitative interpretation is what matters for the policy discussion.
F.4.1.5Exercise 11.5: Carbon-cycle warm-up.¶
Coding exercise driven by notebook lecture_16_01_Climate_Exercise.ipynb. Part (a) avoided-warming and avoided-damages numbers at 2100 under the 50% mitigation rule are notebook outputs and depend on calibration, so they should be reported from the run rather than fixed in the solution text. Part (b) the longest-timescale reservoir is identified by the smallest non-zero eigenvalue of the carbon-cycle transition matrix; for the CDICE three-box calibration this is the lower-ocean compartment, with a multi-century characteristic timescale. Part (c) a quadratic damage function has bounded curvature in and therefore underweights tail risk: marginal damage grows only linearly, so very high realizations of are penalized far less than under super-quadratic damages or an explicit tipping-hazard term, and tail-risk assessment requires one of those richer specifications (compare Exercise 11.8).
F.4.1.6Exercise 11.6: Deterministic CDICE-DEQN reproduction.¶
Coding exercise driven by notebook lecture_16_02_DICE_DEQN_Library_Port.ipynb. The verification target is the set , each compared against the reference solution at the tolerances stated in the notebook’s verification gate. Reference numbers depend on seed, hardware, optimizer schedule, and trajectory sampling, so the solution should anchor on the verification gate rather than on fixed numbers. Typical convergence problems trace back to scaling differences across the eight residuals or to insufficient trajectory coverage near the carbon-stock saturation regime; the residual-balancing methods discussed in Chapter Chapter 4 are the first line of defense.
F.4.1.7Exercise 11.7: Stochastic SCC fan chart.¶
Coding exercise driven by notebook lecture_16_03_Stochastic_DICE_DEQN.ipynb. As the AR(1) productivity volatility rises, the right tail of the SCC distribution at 2100 widens disproportionately, because higher productivity raises emissions which feed convexly into damages. Report the quantiles of the SCC fan chart at each rather than the mean alone, since the mean obscures the asymmetry. The qualitative finding aligns with Cai & Lontzek (2019), that productivity and consumption-growth shocks shift the SCC distribution materially and not just its location, supporting the use of distribution-aware reporting in policy work.
F.4.1.8Exercise 11.8: Tipping-point regime-switching damages.¶
Coding exercise. Report the unconditional tipping probability by 2100, the SCC at , and the optimal abatement path under the regime-switching specification and under the smooth-damage baseline. The expected qualitative pattern is that adding an irreversible tipping hazard raises the SCC and brings abatement forward, especially when is low. The factor by which the SCC rises is an output of the hazard calibration and retrained policy. The policy implication should be framed as a precautionary motive under threshold uncertainty, not as a universal numerical multiplier.
F.4.1.9Exercise 11.9: Real options value of waiting.¶
(i) Closed forms. Under the act-now strategy, the planner chooses to minimize . With , the FOC gives . Plugging back, expected cost is
Under the wait strategy, after observing , the posterior mean has variance shrunk relative to the prior. The planner chooses . Expected cost (using the law of total variance):
(ii) Value of waiting. Difference:
As the signal becomes informative (), , so , and : waiting is preferred. The reduction in posterior variance is the value of information.
F.5(iii) With irreversibility. Add a wedge to the wait-branch objective, so the planner who waits solves a different second-period problem: Assuming the interior solution remains in , $$\mu_1^{\eta\star}(\widehat{\mathrm{ECS}})¶
F.6\frac{\alpha,\mathbb{E}[\mathrm{ECS}\mid\widehat{\mathrm{ECS}}]}{2(\theta+\eta)}C_\mathrm{wait}^\eta¶
\alpha \overline{\mathrm{ECS}}
F.6.1\frac{\alpha^2}{4(\theta+\eta)} \bigl(\overline{\mathrm{ECS}}^2+\mathrm{Var}\mathrm{prior}-\mathrm{Var}\mathrm{post}\bigr).\mathrm{VoW}^\eta = C_\mathrm{wait}^\eta - C_\mathrm{now} = \frac{\alpha^2}{4} \left[ \frac{\overline{\mathrm{ECS}}^2}{\theta}¶
\frac{\overline{\mathrm{ECS}}^2+\mathrm{Var}\mathrm{prior}-\mathrm{Var}\mathrm{post}}{\theta+\eta} \right].$\eta\mathrm{VoW}^\eta>0$: the option value of waiting is dominated by the irreversibility penalty, and act-now is preferred.
F.7The threshold occurs at $$\eta^\star¶
\frac{\theta(\mathrm{Var}\mathrm{prior}-\mathrm{Var}\mathrm{post})} {\overline{\mathrm{ECS}}^2},$$ where the value of information just balances the irreversibility cost.
Connection to climate policy. This stylized model captures the central tension in climate policy: information arrives over time about ECS, damage functions, and tipping thresholds, but emissions are largely irreversible (atmospheric CO persists for centuries). The chapter’s Bayesian-learning treatment makes the trade-off quantitative: under fast learning and slow climate dynamics, waiting can be optimal; under slow learning and fast tipping risks, an early-action premium emerges. The empirical literature Pindyck, 2007Cai & Lontzek, 2019 finds that for realistic climate calibrations, the irreversibility channel typically dominates, supporting near-term carbon tax implementation rather than “wait and see” policies.
F.7.1Chapter Chapter 12: Synthesis and Outlook¶
F.7.1.1Exercise 12.1: Method-choice scenario.¶
Sketch:
(a) 4-state monetary-policy DSGE with smooth shocks. Use classical perturbation or projection as the baseline. The state space is small and the shocks are smooth, so a classical method is transparent, fast, and easy to audit. A DEQN becomes attractive only if the model is extended with genuinely global nonlinearities (for example a binding zero lower bound, occasionally binding collateral constraints, or a highly non-quadratic loss). Hybrid: use a GP surrogate over policy-rule parameters after the classical or DEQN solution step if many counterfactuals are needed.
(b) 200-agent OLG with progressive taxation. Use DEQN with Young’s-method aggregation (Chapter Chapter 5, Chapter 6). 200 cohorts is at the edge where explicit-panel methods (all-in-one DL) and histogram methods compete; histograms are easier when constraints bind frequently across cohorts. Hybrid: post-train a GP surrogate over the Pareto-weight calibration to evaluate optimal-tax-rule sensitivity.
(c) Exotic option pricing on an irregularly shaped payoff. Use PINN or Deep Galerkin methods with careful treatment of the payoff kink (Chapter Chapter 7) for a single-contract instance, or DeepONet if prices are needed for many strikes or contract parameters. The non-smooth object is the terminal payoff, not a generic spatial boundary; for a strong-form Black--Scholes residual this usually calls for smoothing the payoff, using smooth activations away from the kink, or switching to a weak/viscosity-aware formulation. GP surrogates can help as an outer pricing surface over a few parameters, but they are not the primitive PDE solver.
(d) Climate-IAM where SCC uncertainty is the deliverable. Use the full pipeline: DEQN to solve the deterministic IAM, GP surrogate over deep-uncertain parameters (ECS, damage convexity, tipping thresholds), Sobol/Shapley sensitivity decomposition for attribution, and BAL for sample-efficient uncertainty quantification (Chapters Chapter 11, Chapter 9). This combines the IAM uncertainty-quantification workflow of Friedl et al. (2023) with the surrogate-based policy-search logic in Kübler et al. (2026).
F.7.1.2Exercise 12.2: When NOT to use deep learning.¶
Open-ended. Sketch of one regime: bit-exact reproducibility for regulatory audit. GPU non-determinism in atomic accumulators (described in Appendix E) means that a deep-learning solver typically cannot reproduce the same numbers across hardware platforms; for regulatory work where auditors must replay every step bitwise, a deterministic finite-difference solver on a fixed grid is preferable. Even when deterministic flags are set, BLAS implementations differ across CUDA versions. Classical fixed-grid methods are easier to make bit-reproducible because the operation order can be pinned and the solver path is usually far less sensitive to random initialization and stochastic mini-batches.
F.7.1.3Exercise 12.3: Reproducibility audit.¶
Coding exercise. Expected behavior: re-running notebook lecture_03_02_Brock_Mirman_Uncertainty_DEQN.ipynb on the same machine with the same seeds should reproduce the reported diagnostics within the stated tolerance. Bitwise equality of trained network parameters should be expected only when deterministic framework settings, hardware, BLAS/CUDA versions, and floating-point order of operations are all pinned. Re-running on a different GPU, or with deterministic flags off, can produce small deviations in the last few printed digits of the savings-rate diagnostics while remaining well within the residual tolerance of the training.
F.7.1.4Exercise 12.4: Open-ended.¶
Open-ended; expected output is a 1--2 page research sketch. A representative answer combines DEQN (for solving the model) with GP surrogates (for parameter estimation): e.g., a 6-month project that estimates a heterogeneous-agent NK model with deep-learning policy functions, then uses a deep-kernel GP surrogate to do Bayesian posterior inference on the structural parameters. This integrates Chapters Chapter 6, Chapter 9, and Chapter 10.
F.7.1.5Exercise 12.5: Hybrid pipeline DEQN GP SMM.¶
Coding exercise. Illustrative outputs to benchmark against, not fixed targets:
Step 1 (DEQN training). Report the actual training time for the parameterized network. Adding as inputs increases the network’s effective input dimension from 2 to 4, so convergence can be slower than in the single-calibration case.
Step 2 (moment grid). Report the time for the simulations, each with periods, under the trained policy.
Step 3 (GP fitting). Report the fitting time for a four-output GP on 400 training points in .
Step 4 (SMM optimization with GP). Report the number of objective evaluations, optimizer iterations, and total GP-evaluated SMM time.
Naive SMM benchmark. Compare with a version that re-solves or re-trains the DEQN at each candidate only if that benchmark is computationally feasible; otherwise estimate its cost from one representative re-solve.
The expected qualitative result is that the surrogate-based optimization is much cheaper per objective evaluation after the one-time DEQN, simulation-grid, and GP-fitting costs have been paid. The actual speedup and estimation errors are outputs of the run and should be reported rather than assumed.
F.7.1.6Exercise 12.6: DeepONet for a parameterized HJB.¶
(i) Architecture. Branch net encodes the parameter into a -dimensional latent representation; trunk net encodes the query point into the same latent dimension. Predicted value:
where is a learnable scalar bias. Both nets are typically MLPs with 2--4 layers and width 50--200. The architecture is non-trivial because it imposes the bilinear separable structure , which is the universal approximation form for nonlinear operators.
(ii) UAT for operator learning. Lu et al. (2021) show that a continuous nonlinear operator can be approximated uniformly on a compact set of input functions and a compact output domain by a DeepONet with finitely many sensors, a branch network, and a trunk network. In the present notation, for every there are sensor locations, finite-width branch/trunk nets, and latent dimension such that
on the compact training domain , provided the solution operator is continuous there. This generalizes ordinary universal approximation from finite-dimensional functions to operators, but it does not provide extrapolation guarantees outside the compact training domain.
(iii) Cost comparison. Independent PINN runs cost . One DeepONet run costs , where captures the larger network, the parameter-sampling overhead, and the longer training needed to span the parameter range. Operator learning wins exactly when
At , the break-even ratio is therefore 50: a DeepONet can cost up to fifty single-parameter PINN solves and still be cheaper in total. The realized speedup is an empirical output of the implementation, not a universal constant.
(iv) Limitations. Extrapolation: DeepONet trained on has no guarantees outside this range; in practice the predicted operator for degrades smoothly but may violate the structural property that should remain concave. Mitigation: use polynomial-augmented branch networks that extrapolate via known tails (e.g., Bernoulli polynomials), or refuse to predict outside the convex hull of training values.
Concavity preservation: the bilinear DeepONet architecture does not automatically preserve concavity in . A trained network may produce non-concave for some , which is economically wrong under risk-averse preferences. Mitigation: use an input-concave architecture for the trunk representation, for example the negative of an input-convex neural network where appropriate, or add a concavity penalty to the loss. Both increase training cost but restore pressure toward the structural property.
- Backus, D. K., Kehoe, P. J., & Kydland, F. E. (1992). International real business cycles. Journal of Political Economy, 745–775.
- Bergstra, J., & Bengio, Y. (2012). Random Search for Hyper-Parameter Optimization. Journal of Machine Learning Research, 13, 281–305.
- Zaheer, M., Kottur, S., Ravanbakhsh, S., Póczos, B., Salakhutdinov, R., & Smola, A. J. (2017). Deep Sets. Advances in Neural Information Processing Systems (NeurIPS).
- Sirignano, J., & Spiliopoulos, K. (2018). DGM: A Deep Learning Algorithm for Solving Partial Differential Equations. Journal of Computational Physics, 375, 1339–1364.
- Lu, L., Jin, P., Pang, G., Zhang, Z., & Karniadakis, G. E. (2021). Learning nonlinear operators via DeepONet based on the universal approximation theorem of operators. Nature Machine Intelligence, 3(3), 218–229. 10.1038/s42256-021-00302-5
- Achdou, Y., Han, J., Lasry, J.-M., Lions, P.-L., & Moll, B. (2022). Income and wealth distribution in macroeconomics: A continuous-time approach. The Review of Economic Studies, 89(1), 45–86.
- Sherwood, S. C., Webb, M. J., Annan, J. D., Armour, K. C., Forster, P. M., Hargreaves, J. C., Hegerl, G., Klein, S. A., Marvel, K. D., Rohling, E. J., Watanabe, M., Andrews, T., Braconnot, P., Bretherton, C. S., Foster, G. L., Hausfather, Z., von der Heydt, A. S., Knutti, R., Mauritsen, T., … Zelinka, M. D. (2020). An Assessment of Earth’s Climate Sensitivity Using Multiple Lines of Evidence. Reviews of Geophysics, 58(4), e2019RG000678. 10.1029/2019RG000678
- Cai, Y., & Lontzek, T. S. (2019). The Social Cost of Carbon with Economic and Climate Risks. Journal of Political Economy, 127(6), 2684–2734. 10.1086/701890
- Pindyck, R. S. (2007). Uncertainty in Environmental Economics. Review of Environmental Economics and Policy, 1(1), 45–65.
- Friedl, A., Kübler, F., Scheidegger, S., & Usui, T. (2023). Deep Uncertainty Quantification: With an Application to Integrated Assessment Models.
- Kübler, F., Scheidegger, S., & Surbek, O. (2026). Using Machine Learning to Compute Constrained Optimal Carbon Tax Rules. Journal of Political Economy: Macroeconomics.