26.2 Numerical Solvers
Anyone who has trained a network has seen a run blow up because the learning rate was too large. It is tempting to blame the loss surface, with its sharp valleys and its plateaus. Yet the same thing happens on the simplest loss there is. Gradient descent on the bowl takes the step , and for every learning rate above the iterates grow without bound, although the bowl has a single minimum and nothing about it is difficult. If the loss is not the problem, what is?
The answer comes from an older subject. Gradient descent is a step-by-step solution of the differential equation , which says: move downhill at a speed proportional to the slope. This is the decay equation solved in Section 26.1, fifty times faster, and its exact solution decays to zero from every start. Euler proposed in 1768 to solve such an equation by following the arrow for a short time and then reading it again, and the learning rate plays the role of . One step multiplies by . With the factor is , and the computed solution decays like the true one. With it is , where the exact factor is , and the computed solution flips sign and grows. The equation is stable; the steps are not. In the previous section the eigenvalues of an equation gave its exact motion. Here the same eigenvalues decide how large a step can follow that motion.
Deep learning meets this gap between an equation and its steps wherever it takes steps: in gradient descent (Section 9.1), in the layers of a residual network (Section 7.4), and in the samplers of diffusion and flow-matching models (Section 17.5). A sampler evaluates a network once or twice in every step, so the number of steps sets the cost of an image.
Three questions decide what a step-by-step solution is worth. How far does it stray from the true one? How can it stray less for the same work? And how long may a step be before the errors grow instead of dying out? It turns out that one object answers all three: the factor by which a step multiplies the solution, which for Euler on the bowl was . At the end we return to gradient descent and ask what a better solver would do for training.
26.2.1 Forward Euler#
A trajectory is its start plus the velocity accumulated on the way. Over a short step, Euler's proposal is the crudest one possible: pretend that the velocity keeps the value it has at the start. Let us first see what this does on an equation whose answer we know.
Take from to , where the answer is . Divide the interval into steps of length , and in each step move with the velocity at its start: . After steps, . This is a dollar at 100% annual interest compounded times a year:
| 1 | 2 | 4 | 8 | 16 | 32 | 365 | |
|---|---|---|---|---|---|---|---|
| 2.000 | 2.250 | 2.441 | 2.566 | 2.638 | 2.677 | 2.7146 | |
| error | 0.718 | 0.468 | 0.277 | 0.153 | 0.080 | 0.041 | 0.0037 |
The ratios of consecutive errors are : doubling the number of steps comes closer and closer to halving the error. Even daily compounding falls more than a third of a cent short of dollars.
We have met this slow limit before. The compounding of Section 26.1 was Euler's method before it had a name: steps of length along a linear field. The expansion found there, , gives the dollar's error with . It is about . Error proportional to is what we will call order one.
For a general field , with step size and grid , where from here on counts the steps taken so far, forward Euler is
The method follows the arrow at the current point for time , then reads the field again. Equivalently, it is the Taylor expansion of the true solution cut after the linear term, and the error of one step is the first term dropped. If along the solution, then
The remainder is the local error: what one step loses when it starts on the true solution. What we want to know is the global error, the distance from the true solution after all the steps to a fixed horizon . A local error of order does not give a global error of order . Reaching takes steps, their local errors accumulate, and each step may amplify the error already made. One power of is lost. The proof is short, and its structure matters more than its constant.
Proposition (Euler converges at order 1). Let be -Lipschitz in , that is for all , and , and let the solution of from satisfy on . Then the Euler iterates (26.2.1) from the same start obey
Proof. Let , and subtract the Taylor identity above from the update (26.2.1):
Each step multiplies the existing error by at most and adds at most . Unrolling the recursion from sums a geometric series:
using .
For on we have and , so the bound is , against the true error : the right order, with a pessimistic constant. The structure of the bound recurs for every solver. A local error of order per step becomes a global error of order after steps, inflated by the factor that measures how strongly the dynamics amplify old mistakes. A method with global error of order has order ; Euler has order .
The factor is the crude part. The constant records how steep the field is and not which way it leans, so the bound cannot tell a field that drives trajectories apart from one that pulls them together. For the bowl's equation on the factor is , useless at any step a computer could take, although small steps follow the decay well. A field that contracts needs an analysis of its own, and we come to it after raising the order.
26.2.2 Runge--Kutta Methods#
Euler commits to the slope at the start of the step while the trajectory curves away from it. Runge--Kutta methods measure the slope at points inside the step and combine the measurements. Figure 26.2.1 shows one step of size on from .
One step of size on from . (a) Euler follows the starting slope and lands at . (b) The midpoint method takes a half step only to measure the slope there, , and lands at . (c) RK4 measures four slopes, , , and , averages them with weights and lands at ; the exact value is .
26.2.2.1 Midpoint, Heun and RK4#
The simplest improvement, the midpoint method, takes half an Euler step only to measure the slope there, and then takes the real step with that slope. Writing for a field that does not depend on time, it is . One Taylor line in one dimension shows why it helps:
The true expansion is with , so the term is now right instead of missing. The local error is and the global order , for two field evaluations per step.
The midpoint method spends its first evaluation on a half step. Heun's method takes a full trial Euler step instead and averages the slopes at the two ends of the step:
If the midpoint method is the midpoint rule for an integral, this is the trapezoid rule. The same Taylor line gives it the same order , at the same two evaluations. Heun's method is the one to remember of the two, because many diffusion samplers use it (Section 17.5).
Four slope measurements give the standard general-purpose method of scientific computing, classical Runge--Kutta (RK4), which goes back to Kutta in 1901:
The update averages four slope measurements, weighting the two at the midpoint twice. These are the weights of Simpson's rule, , which integrates cubics exactly, with the midpoint's share split between two measurements.
26.2.2.2 The Stability Function#
Why order ? On a linear field the answer takes one computation. Consider the scalar equation , with real or complex. It is known as the test equation, and it stands for every linear field at once: each mode of obeys it, with an eigenvalue of (Section 26.1). Its true solution gains the factor over a time . Each method multiplies by a fixed function of per step, and we can compare that function with .
Proposition (stability functions). On the test equation, with , one step of each method multiplies by its stability function :
Proof. For RK4 the four measurements are , , and , each obtained by substituting the previous one. The update is , which is the stated polynomial times . For Euler, . For the midpoint method, , and for Heun, ; both are .
Each is the Taylor polynomial of the exact factor , cut at the method's order. For RK4, , so on this equation one step errs by and steps by . For nonlinear fields that are four times continuously differentiable and Lipschitz in , a longer Taylor match gives the same orders: midpoint and Heun have order , RK4 order (Hairer et al., 1993). We do not prove this; the expansion of four nested evaluations fills pages and teaches little. The stability function is the object to keep from this section. How closely it follows near is the accuracy of a method, and how large it becomes far from zero will decide which steps are stable.
26.2.2.3 Order at Equal Cost#
It remains to measure the orders, and to compare the methods at the same
number of field evaluations. In code the two ends of the family take a few
lines each, for a field f that does not depend on time.
def euler(f, x0, T, n):
"""Forward Euler: n steps of size h = T/n."""
x, h = np.asarray(x0, dtype=float), T / n
for _ in range(n):
x = x + h * f(x)
return x
def rk4(f, x0, T, n):
"""Classical Runge-Kutta: four slope measurements per step."""
x, h = np.asarray(x0, dtype=float), T / n
for _ in range(n):
k1 = f(x)
k2 = f(x + 0.5 * h * k1)
k3 = f(x + 0.5 * h * k2)
k4 = f(x + h * k3)
x = x + (h / 6) * (k1 + 2 * k2 + 2 * k3 + k4)
return x
On log--log axes, is a line of slope , so the measured slopes should be and . We test this on the spiral of Figure 26.1.1, whose eigenvalues are . A point on it loses length at rate while it turns at unit speed, so from the exact state at is , of length (Section 26.1).
A = np.array([[-0.5, -1.0], [1.0, -0.5]]) # the spiral, eigenvalues -0.5 +- i
x0, T = np.array([2.0, 0.0]), 2.0
x_true = np.exp(-1) * np.array([2 * np.cos(2), 2 * np.sin(2)]) # e^{AT} x0
On a linear field we can predict the constants as well as the slopes. On the spiral a step of either solver is a rotation combined with a rescaling, as the exact motion is. A solver whose factor is off by some fraction in each mode is therefore off by the same fraction of the length of the true endpoint. For Euler the fraction is the one found for the compounding, . Here , so Euler should miss by of the length, that is by .
For RK4 the fraction comes from the stability function. One step is off by the fraction , with , and the errors of steps add. The sum is of the length, or . The cell halves the step six times, from steps to .
f = lambda x: A @ x # the spiral field
ns = 2 ** np.arange(3, 10) # 8, 16, ..., 512 steps
hs = T / ns
err_eu = np.array([np.linalg.norm(euler(f, x0, T, n) - x_true) for n in ns])
err_rk = np.array([np.linalg.norm(rk4(f, x0, T, n) - x_true) for n in ns])
print('measured slope, Euler:', f'{np.polyfit(np.log(hs), np.log(err_eu), 1)[0]:.3f}')
print('measured slope, RK4 :', f'{np.polyfit(np.log(hs), np.log(err_rk), 1)[0]:.3f}')
print(f'error at 512 steps: Euler {err_eu[-1]:.1e}, RK4 {err_rk[-1]:.1e}')
print('RK4 with 128 steps (the same 512 evaluations):',
f'{np.linalg.norm(rk4(f, x0, T, 128) - x_true):.1e}')
d2l.plot(hs, [err_eu, err_rk, err_eu[-1] * (hs / hs[-1]),
err_rk[-1] * (hs / hs[-1]) ** 4],
'step size h', 'global error at T', xscale='log', yscale='log',
legend=['Euler', 'RK4', 'slope 1', 'slope 4'])measured slope, Euler: 1.040
measured slope, RK4 : 4.022
error at 512 steps: Euler 3.6e-03, RK4 5.0e-12
RK4 with 128 steps (the same 512 evaluations): 1.3e-09
The fitted slopes are and , a little above and because the fit includes steps as coarse as , where the next terms of the expansions still count. At steps the errors are and , which is what and predict. The slopes hide the cost, though. RK4 reads the field four times per step, so a fair comparison gives it a quarter of the steps. With the same field evaluations, that is steps, RK4 reaches , six orders of magnitude below Euler. To match that, Euler's law asks for more than a billion steps. In general a method of order needs a number of steps proportional to for an error .
Practical solvers also choose the step size as they go. An embedded pair such as Dormand--Prince computes solutions of orders and from the same evaluations and takes their difference as an estimate of the local error (Dormand and Prince, 1980). The solver then shortens the step where the estimate is large and lengthens it where the estimate is small. Exercise 1 builds the simplest such controller.
All these methods start every step afresh and discard the slopes that the step before has measured. A multistep method keeps them. The simplest one, the two-step Adams--Bashforth method, reads the field once per step and extrapolates from the last two readings:
The bracket is , the line through the two readings followed for half a step more. It is an estimate of the slope at the middle of the coming step, so this is the midpoint method with the midpoint slope taken from memory and not from a second evaluation: order at the cost of Euler. Two things are lost. The first step has no predecessor and must be taken by a one-step method, and the weights and hold for equal steps only and must be recomputed when the step size changes. Where one evaluation is a pass through a large network, the saving outweighs both, and the multistep samplers of Section 17.5 are built on this step.
26.2.3 Stiffness and Implicit Methods#
Order measures how accurate a step is when it is small. Stability asks a different question: whether the errors of many steps die out or compound. For Euler and RK4 the answer caps the step size, however little accuracy we need.
The smallest system that shows the problem has two decoupled modes, from , followed to . By then the fast mode has decayed to and the slow one stands at . After only the slow mode is left, and steps of would follow it well. Yet the fast coordinate is the opening's equation , and Euler multiplies it by at every step for as long as we integrate. A system is stiff when some Jacobian eigenvalues have large negative real parts compared with the rate at which the solution of interest varies: a mode that is long gone still sets the step.
Which steps are allowed? The stability function answers. On the test equation , whose solution decays if and only if , a method turns into after steps. The computed mode therefore decays if and only if . For forward Euler this reads , and for a real it is , or
For the bowl, is the learning rate above which the iterates of the opening grew.
Below the limit we also get what the error bound of Euler's method lacked, an analysis for a field that contracts. A step now multiplies the error already made by , where the general proof could only bound this factor by . For the geometric sum of that proof stays below , and the bound becomes : the old bound without its exponential. For the bowl's equation from , where , that is , within a factor of three of the true error.
26.2.3.1 Backward Euler#
A shorter step is one way out. The other looks odd at first: take Euler's step with the slope at the end of the step,
This is backward Euler. The unknown stands on both sides, a nuisance we postpone until we have seen what the method achieves.
Proposition (backward Euler is stable at every step). On the test equation with , backward Euler has the stability function , and for every step .
Proof. One step is , so , and when .
The reason can be seen without the algebra. Forward Euler extrapolates with the slope at the point where it stands, and on a steep mode that slope, held for a long step, carries it far past zero. Backward Euler asks for the point whose own slope leads back to where we are. A point that has almost decayed has almost no slope, so no step is long enough to overshoot.
Now for the nuisance: the field is evaluated at a point that is not yet known, so each step is an equation to solve, a linear system when the field is linear and a few Newton iterations otherwise (Exercise 3). Such methods are called implicit; Euler and RK4, which compute the new state by a formula, are explicit. An implicit step is worth its solve when stability, not accuracy, would set the step of an explicit method.
We now run both methods on the two-mode system at five step sizes, backward Euler with one linear solve per step. The reader can predict the first row: at forward Euler multiplies the fast coordinate by ten times.
def backward_euler_linear(A, x0, T, n):
"""Backward Euler on dx/dt = A x: solve (I - h A) x_new = x at each step."""
x, h = np.asarray(x0, dtype=float), T / n
for _ in range(n):
x = np.linalg.solve(np.eye(len(x)) - h * A, x)
return x
A_stiff = np.diag([-50.0, -1.0]) # one fast mode, one slow mode
x0_stiff = np.array([1.0, 1.0])
T = 1.0
print(f'exact at T = 1: fast {np.exp(-50):.1e}, slow {np.exp(-1):.4f}')
print(f'{"h":>5} {"fwd fast":>10} {"fwd slow":>9} {"bwd fast":>10} {"bwd slow":>9}')
for n in [10, 20, 25, 50, 100]:
fwd = euler(lambda x: A_stiff @ x, x0_stiff, T, n)
bwd = backward_euler_linear(A_stiff, x0_stiff, T, n)
print(f'{T / n:5.2f} {fwd[0]:10.1e} {fwd[1]:9.4f} {bwd[0]:10.1e} {bwd[1]:9.4f}')
exact at T = 1: fast 1.9e-22, slow 0.3679
h fwd fast fwd slow bwd fast bwd slow
0.10 1.0e+06 0.3487 1.7e-08 0.3855
0.05 3.3e+03 0.3585 1.3e-11 0.3769
0.04 -1.0e+00 0.3604 1.2e-12 0.3751
0.02 0.0e+00 0.3642 8.9e-16 0.3715
0.01 7.9e-31 0.3660 2.5e-18 0.3697
At both methods have the slow mode within about of the truth ( and against ), accurate enough for many purposes. Forward Euler nonetheless returns for the fast component, whose true value is . At its factor is the opening's , applied twenty times. At the factor is , and the fast component flips sign at every step and never shrinks. (The zero in the row is exact: there , and one step removes the fast mode.) Forward Euler needs , a step at which its slow mode is already within about . We asked for , and stability made us compute .
Backward Euler is stable at every step size. Its slow-mode error is the error of a first-order method, so stability does not bring accuracy.
26.2.3.2 Stability Regions#
Forward Euler has a step-size limit and backward Euler has none. Where do other methods stand? A plot of the plane shows all of them at once. The stability region of a method is the set where its update decays. A method is A-stable if its region contains the whole open left half-plane : it makes every decaying mode decay, whatever the step (Dahlquist, 1963). Backward Euler is A-stable, since its region is everything outside the closed unit disc around .
Figure 26.2.2 marks the examples. The opening's step on is the point , outside Euler's disc, and is , inside. The spiral, with , gives , which is below if and only if ; at its two points lie on the circle. A pure rotation puts on the imaginary axis, which touches Euler's disc only at the origin, so forward Euler makes an undamped oscillation grow at every step size (Exercises 2 and 4). The exact step of Section 26.1.2.3 has modulus below one on the whole left half-plane, which is the behaviour backward Euler imitates and forward Euler does not.
Stability regions in the complex plane of for the test equation ; a decaying mode sits in the left half-plane. Forward Euler decays only inside the disc , whose real slice is ; RK4 enlarges it to a lobed region reaching on the real axis; backward Euler is stable everywhere except the disc around , in particular on the entire left half-plane, which is A-stability. The marked points are the opening's step, its step, and the spiral at , on the edge of Euler's disc.
No explicit Runge--Kutta method is A-stable, however many stages it has. Its is a polynomial (Exercise 2), and a polynomial other than a constant grows without bound as runs out along the negative real axis. Higher order therefore does not cure stiffness. RK4's region ends on the real axis at , the negative root of . On the bowl's equation it allows where Euler allows , and it reads the field four times per step. This is why implicit methods are kept for stiff fields, while explicit ones are the default everywhere else. The stiff field that readers of this book meet most often is the gradient of a loss whose curvature is large in some directions and small in others.
26.2.4 Gradient Descent as a Solver#
The opening treated one coordinate. With several, the same factor appears once per eigenvalue of the Hessian. Moving downhill continuously on a loss , always along the negative gradient, is the gradient flow
a field that vanishes at the critical points of and along whose trajectories the loss only falls: . Gradient descent with learning rate , , is forward Euler (26.2.1) on this flow with .
Section 23.1 derives the learning-rate ceiling on a quadratic with Hessian and studies the speed below it. We do not repeat the study of the speed. The ceiling we derive once more, in three arrows, because the route is what the solver view adds. Write for the displacement from a minimum with Hessian . Near the minimum the flow linearizes, and each eigenvalue of becomes a decaying mode with rate , a copy of the test equation:
The learning-rate ceiling is thus the boundary of Euler's stability disc, reached by the steepest mode at . The first arrow holds the Hessian fixed, and so the ceiling is a statement about a quadratic. On a network the Hessian moves during training, and a run above the ceiling often does not blow up: its largest eigenvalue comes back toward , and the loss keeps falling over the long run, though not at every step (Section 23.1.2.4).
If this reading is right, the ceiling comes from Euler's method, and another solver must have another ceiling. Let us test this prediction on the valley on which Section 23.1 sweeps the learning rate, with (that section lists the flat coordinate first). Its gradient flow has a steep mode with rate and a flat one with rate . From we take steps of size with three solvers. Forward Euler is gradient descent, with its ceiling at . RK4 reads the gradient four times per step, and since its region reaches on the real axis (Figure 26.2.2), its ceiling should be . Backward Euler, , should have none. For each run the cell prints the factors by which one step multiplies the two modes, and , and the length of the iterate after the steps. The factors are measured, by applying one step to the identity matrix.
H = np.diag([10.0, 1.0]) # Hessian of L(x) = x^T H x / 2
flow = lambda x: -H @ x # the gradient flow
solvers = { # n steps of size eta on the flow
'forward Euler': lambda x0, eta, n: euler(flow, x0, n * eta, n),
'RK4': lambda x0, eta, n: rk4(flow, x0, n * eta, n),
'backward Euler': lambda x0, eta, n: backward_euler_linear(-H, x0, n * eta, n)}
print(f'{"solver":<15}{"eta":>6}{"steep factor":>14}{"flat factor":>13}{"||x_100||":>12}')
for name, eta in [('forward Euler', 0.19), ('forward Euler', 0.21), ('RK4', 0.27),
('RK4', 0.29), ('backward Euler', 0.25), ('backward Euler', 25)]:
steep, flat = np.diag(solvers[name](np.eye(2), eta, 1)) # one step's matrix
x_100 = solvers[name](np.array([1.0, 1.0]), eta, 100)
print(f'{name:<15}{eta:6.2f}{steep:14.3f}{flat:13.3f}{np.linalg.norm(x_100):12.1e}')
solver eta steep factor flat factor ||x_100||
forward Euler 0.19 -0.900 0.810 2.7e-05
forward Euler 0.21 -1.100 0.790 1.4e+04
RK4 0.27 0.879 0.763 2.5e-06
RK4 0.29 1.187 0.748 2.8e+07
backward Euler 0.25 0.286 0.800 2.0e-10
backward Euler 25.00 0.004 0.038 3.2e-142
Each solver has its own ceiling, where its stability region ends. Forward Euler converges at , with a steep factor of , and diverges at , with . RK4 still converges at and diverges at . Backward Euler converges at , above the ceiling of gradient descent, and at , far above both, where its factors are and and a hundred steps leave nothing measurable of the iterate. The opening asked what the problem is, if it is not the loss. The answer is that the ceiling is a quotient. The loss supplies its denominator, , and the solver supplies its numerator, which is for forward Euler and for RK4. Backward Euler has no ceiling at all.
Should we then train with RK4? No. Its ceiling is times higher and its step takes four gradients, so each gradient advances the flow by at most , against for gradient descent. The extra gradients serve to follow the path of the gradient flow more closely, and an optimizer has no use for the path. It wants the place where the path ends. Nor is leaving the path only an error. To second order in the iterates of gradient descent follow the flow of a modified loss that penalizes large gradients, so the error that Euler makes as a solver acts as a regularizer (Exercise 5).
The two methods also fail differently. Euler's steep factor leaves the stable range through , and the iterate jumps across the valley floor to land higher each time. RK4's factor is positive on the whole real axis and leaves through : at it is , and the iterate walks away from the minimum without once changing sign. The zigzag, too, belongs to Euler's method. Momentum, the usual remedy for it, solves a different equation: Polyak's heavy ball discretizes , the motion of a ball with mass and friction (Polyak, 1964) (Exercise 6).
Backward Euler only improves as the step grows, since its factors shrink. The catch is the solve. Its step says that the gradient of vanishes at , which for a convex loss makes it the proximal step of Section 23.6.4.1, applied to the loss itself. On our quadratic that is one linear system. On a network it is an optimization problem of its own at every step, and for large it is the problem we set out to solve.
The valley is the stiff system of Section 26.2.3 in a milder form, with rates and in place of and , and in place of . At any the flat factor of gradient descent stays above (the table prints at ), so the flat direction loses less than a fifth of its length per step, however well the steep one does. In general it loses less than the fraction , which is a five-hundredth for a condition number of . Stability fixes through , and then sets the speed, so the condition number of the Hessian is the stiffness of the gradient flow. On a quadratic, a diverging learning rate is a solver instability.
We knew the eigenvalues of every field in this section before we took the first step, because we had written the field down ourselves. A field that is a network comes with no such list. Section 26.3 takes a learned field as the model itself, with layers for Euler steps, and asks how such a model is trained and what it does to a probability density.
26.2.5 Summary#
A numerical solver replaces a trajectory by steps, and two properties judge it. Its order says how fast the error falls with the step: a local error accumulates to a global error , with for Euler and for RK4. Its stability region says which steps do not blow up: forward Euler needs , backward Euler is stable on the whole left half-plane and solves an equation at every step, and a system is stiff when a fast mode that has long decayed still sets the step. On a linear field both properties are read from the stability function , the factor by which one step multiplies a mode. Gradient descent is forward Euler on , so its ceiling is the edge of Euler's region, and ill-conditioning is stiffness.
26.2.6 Exercises#
- [code] Adaptive step size. ● An embedded pair estimates the local error from two methods of different order. The simplest pair uses the stages and of Heun's method: the Euler value and the Heun value differ by . A controller accepts the step, keeping the Heun value, when , and in either case continues with the step size
- Which order of the local error does the exponent assume?
- Implement the controller, starting from and shortening the
last step so that it ends at . Integrate the spiral field
ffromx0to for . Count the field evaluations, including those of rejected steps, and compare the error with the exact endpointx_true. How does the number of evaluations scale with ? - Integrate the field of
A_stifffrom to with and plot the accepted step sizes against time. At which value do they settle after the fast mode has decayed? Explain this value with Heun's stability function from (26.2.4).
-
Rotating modes. ● The stiff example has real eigenvalues. A complex eigenvalue enters through , the coordinate of Figure 26.2.2, and its imaginary part can decide whether a step is stable.
- For the spiral field of Figure 26.1.1, with eigenvalues , the text found that forward Euler decays for . Find the largest such step for Heun's method from its stability function in (26.2.4) (the condition is a cubic in ; solve it numerically), and for RK4. Heun's method reads the field twice per step and RK4 four times. Which of the three methods covers the most time per field evaluation without growing?
- For the rotational field , show that forward Euler multiplies by per step and that backward Euler divides it by the same factor. By which factor does each method change over one revolution, that is steps, when ?
- The stability function of RK4 is the last formula in (26.2.4), and its square modulus on the imaginary axis decides rotation. Show that for real , and find the range of for which RK4 does not amplify the rotation.
- An explicit Runge--Kutta method with stages computes for and , as RK4 does in (26.2.3). Show that its stability function is a polynomial in of degree at most . Why does this rule out A-stability for explicit methods?
-
[code] Implicit steps on a stiff nonlinear field. ● The text's stiff system is linear and diagonal, so each backward-Euler step was one linear solve. Take instead the damped pendulum , of Section 26.1.2.5 with the heavy damping , from to .
- Compute the eigenvalues of its Jacobian at the bottom, , and the step-size limits of forward Euler and RK4 that they imply.
- Show that after the fast transient the motion nearly satisfies , and compute from this one-dimensional equation.
- One backward-Euler step solves for . Write Newton's iteration for it, and implement backward Euler with three Newton iterations per step, started from .
- Run forward Euler, RK4 and backward Euler with , , and
equal steps (, , and ), against a
reference computed with
rk4and steps. Which runs blow up, and do the limits of part a predict them? Then find for each method the smallest with an endpoint error below , and count the field and Jacobian evaluations it takes. For which method does accuracy set , and for which does stability?
-
[code] Symplectic Euler and splitting. ● The harmonic oscillator , conserves . Forward Euler spirals out of its circular orbits and backward Euler spirals in. The symplectic Euler update advances with the old and then with the new : , .
- Write the update as a matrix acting on and show that for every , so the update preserves area as the exact flow does, while forward Euler's matrix has determinant .
- Show that the eigenvalues of are distinct and lie on the unit circle if and only if . What happens at and for ?
- Show that is conserved exactly by the update. What does its level set through look like, and how far from the origin can the computed orbit get at and at ? (Hint: the axes of the quadratic form have lengths in the ratio .)
- Integrate from to with forward Euler, backward Euler and symplectic Euler at and , and report the largest and smallest along each run.
- The update is the exact flow of with frozen, for time , followed by the exact flow of with frozen. Write the two generators and , whose sum is the oscillator's matrix, compute , and , and show that differs from by terms of order . The spiral's closed form in Section 26.1 split an exponential without any error. Which property that it used fails here? The symmetric splitting is the leapfrog integrator of Hamiltonian Monte Carlo (Neal, 2011); what is its order?
-
[code] Implicit gradient regularization. ●● Gradient descent is forward Euler on the gradient flow (Section 26.2.4), so each step leaves the flow of by . Backward error analysis looks for a modified field whose exact time- flow agrees with one Euler step up to . Barrett and Dherin (2021) find that for gradient descent this field is again a gradient field, of the modified loss
- Expand the exact flow of over time to second order, and show that . Derive for . Which regions of parameter space does the added term penalize?
- For with , show that the iterates of gradient descent lie exactly on the gradient flow of with . Expand in and compare it with the curvature of .
- Gradient descent on this quadratic still converges for , with iterates that alternate in sign. Trajectories of a scalar autonomous field with a Lipschitz constant cannot cross, so the time- map of such a field preserves order. Conclude that no such field takes the values of the iterates at the times . For a quadratic with Hessian in dimensions, show that for every starting point with a component along the top eigenvector, the iterates lie on the flow of no gradient field once .
- For and , run gradient
descent to with . Compute the
gradient flows of and of to
with
rk4and many steps, the latter separately for each . Fit the slopes of the two endpoint errors of gradient descent against .
- Heavy ball as a discretized ODE. ● Heavy-ball momentum
discretizes the equation
of a ball with mass and friction .
- Replace by the central difference and by the backward difference . Show that the result is the heavy-ball update, and express and through , , and .
- For the ODE is a damped oscillator, critically damped at . Express this condition through , , and . The heavy-ball recurrence is critically damped when its characteristic polynomial has a double root. Find the corresponding and compare the two conditions for small .
- The heavy-ball recurrence on this quadratic converges if and only if for (Exercise 8a of Section 23.1 asks for the proof). Translate the condition into one on , , , and . The ODE decays for every , but its discretization does not. What is the largest stable step as , in terms of the angular frequency of the oscillator? Which eigenvalue of the Hessian of an ill-conditioned quadratic sets the step limit?