---
name: learned-rk
description: "Get more accurate fixed-step solutions for a recurring family of smooth, non-stiff ODEs at the same number of right-hand-side calls per step. Use representative equations and initial states, a deployment step size or range, and accurate one-step targets or Taylor derivatives to fit an explicit Runge–Kutta tableau once. Choose the stage count and verify the fitted order on that family. Guo et al. call this RK-NN."
---

# Family-trained explicit Runge–Kutta

## 1. What this solves

If you solve many related differential equations, you can pay once to tune an integrator and reuse it on each new solve. The aim is to reduce error at your fixed step size while keeping the same number of evaluations per step as an ordinary integrator.

For initial-value problems $y'=f(y)$, Guo et al. fit the entries of one explicit Runge–Kutta (RK) tableau across a distribution of tasks $(f,y_0)$ and step sizes. Their training architecture is called RK-NN. Deployment uses the fitted tableau and evaluates the given $f$ of each new task.

Earlier work optimized classical RK coefficients or learned them with neural networks. This skill covers the variant Guo et al. developed for a distribution of ODE tasks, with a Taylor-derivative penalty whose targets can be computed from the RHS without trajectory labels. See the paper's §5 and the sources below.

## 2. When to use

- You can sample the smooth, non-stiff right-hand sides and initial states you will actually solve. For example, one model with a distribution of rate constants and initial loads can define a family. Sharing a state dimension or a field of application is insufficient evidence for transfer.
- You know the fixed deployment step size or range, can supply accurate one-step targets or Taylor derivatives, and can test held-out equations and complete trajectories. Cover the states visited during the rollout, especially if trajectories move far from their starts.
- The volume of reuse justifies reference solves, differentiation, fitting and validation. Compare with a classical solver at the same stage count and step size. If both meet the tolerance, compare total cost to meet it, including training. A learned method with the same number of stages has the same number of RHS calls per step.
- The authors measured per-epoch work growing between $O(d)$ and $O(d^2)$ on their two examples. They reported 187–201 epochs for the linear family and 1,506–2,336 for the nonlinear family across the tested dimensions. Use these as examples of training cost. Time your own RHS, target generation and differentiation. See Remark 1 and SM5, Fig. 16 and Table 2.

## 3. When not to use (and what to use instead)

| Situation | Use instead |
| --- | --- |
| One-off solve, unrelated ODEs, or no reliable reference data | `rk4` on a trusted fixed grid, or `explicit-midpoint` when limited to two stages. |
| Changed equations, parameters, initial states or step sizes without validation | Use a classical solver until the new regime has been checked, or retrain on a representative family. A fitted tableau can give higher error than a classical tableau of the same order and stage count. See §§4.1, 4.2 and 4.4 (Figs. 2, 3 and 6–8) and SM2–SM3. |
| Stiff dynamics at the required step | Use `backward-euler` for strongly decaying modes when first-order accuracy suffices, or an implicit stiff solver such as Radau IIA or BDF. A finite-stage explicit tableau has a polynomial stability function and conditional stability. |
| The solver must choose steps from an error tolerance, locate events or supply dense output | `dormand-prince-rk45` for non-stiff ODEs. |
| A general order guarantee or long-term preservation of Hamiltonian structure is required | Use a classical tableau of proven order, or `stormer-verlet` or `implicit-midpoint` for suitable Hamiltonian problems. |

## 4. Algorithm

Equation and figure numbers here refer to arXiv v3.

1. **Choose the training distribution.** Sample a right-hand side $f$, a starting state $y$, and a positive step $h$ from the intended regime. For one deployment step, use that value for the finite-step term. Keep tasks for validation and final testing separate from fitting.
2. **Build one shared explicit tableau.** Use $s$ stages and a strictly lower-triangular matrix $A=(a_{ij})$. Train its entries and unconstrained output logits $z_i$. With $m=\max_j z_j$, set

   $$b_i=\frac{\exp(z_i-m)}{\sum_j\exp(z_j-m)}.$$

   For each sample evaluate the stages in order and take the weighted step.

   $$K_i=f\left(y+h\sum_{j<i}a_{ij}K_j\right),\qquad \Phi_h(y)=y+h\sum_{i=1}^s b_iK_i.$$

   This is Eq. (11) and §3.1. Here $K_i$ is an unscaled derivative. The paper also writes increments $k_i=hK_i$. Use one convention throughout. The softmax gives positive weights and $\sum_i b_i=1$, making the method consistent (Proposition 3.1). For smooth problems this guarantees at least first-order classical convergence under the usual finite-time stability assumptions. Stage entries can be negative. The softmax permits weights near zero but excludes exact zero and negative weights.
3. **Form a batch objective.** Let $Y_h$ be the exact or accurate reference one-step state and $B_h$ the one-step state of a classical RK baseline from the same $y$. Section 3.2 uses an RK method of the target order for this scaling, for example RK3 when $p=3$. Implement Eqs. (13)–(16) and Algorithm 1 with a Euclidean norm in both terms. Write $e(h)=Y_h-\Phi_h(y)$ for the one-step error and $e^{(k)}(0)$ for its $k$th derivative in $h$ at $h=0$.

   $$L_h=\frac{\|e(h)\|_2^2}{\|Y_h-B_h\|_2^2},\qquad R=\sum_{k=1}^p\|e^{(k)}(0)\|_2^2.$$

   The reference follows the scaled loss in Eq. (14), interpreting its unspecified norm as Euclidean. Figure 9a discusses an unscaled MSE diagnostic. The authors' research code uses coordinatewise scaling and also normalizes the Taylor residuals. The reference exposes optional weights as an implementation choice. Minimize the sample mean of $w_LL_h+w_RR$, defaulting to $w_L=w_R=1$, and skip any term with zero weight. Compute a ratio per task before averaging. Check that the baseline error is resolved above reference-target uncertainty and floating-point resolution.

   Obtain exact flow derivatives recursively by $D_1=f$, $D_{k+1}(y)=J_{D_k}(y)f(y)$, where $J_{D_k}$ is the Jacobian. You can equivalently expand the flow as a power series. Set its constant term to the starting state and solve for each next coefficient from the ODE.

   $$[h^{k+1}]Y(h)=\frac{[h^k]f(Y(h))}{k+1}.$$

   Evaluate the same RK stages with $h$ as a truncated series, then multiply each order-$k$ coefficient of both series by $k!$ to get the derivatives used in $R$. The paper also allows a sufficiently accurate Taylor surrogate for the finite-step target (Eq. (15)).
4. **Fit and freeze.** The paper uses Adam. Algorithm 1 stops when the mean scaled one-step error $\gamma$ falls below $\epsilon$ or the iteration budget runs out. Monitor order residuals and held-out rollouts before choosing a checkpoint. Export $A,b$, and run the ordinary explicit RK step at the fixed deployment $h$. Use the same tableau across all tasks and steps.

**Order at steps smaller than the training range.** An explicit method with $s$ stages reaches classical order $s$ for $s\le4$, order 4 with five stages and order 5 with six. A higher $p$ is reachable only through special structure of the family, as in the two-stage square example below. Neither term of the paper's loss holds any order exactly. The finite-step term rewards accuracy at the training steps, not at smaller ones. When $p$ is out of reach, the unweighted Eq. (16) penalty lets the optimizer give up the lower orders to shrink the largest, top-order residual. The fitted tableau then matches the derivative orders only approximately, so its error stops falling like $h^p$ at small steps. With the finite-step term this happens even when $p$ is reachable. `verify/check_order_target.py` shows it on a pendulum family with three stages. Errors are on new tasks from the same family, relative to RK3.

| Setting | $h=0.05,\ 0.025$ (training range) | $h=5\times10^{-4}$ |
| --- | --- | --- |
| Taylor term only ($w_L=0$), $p=4$, as in Eq. (16) | 11–126 times worse | over $10^5$ times worse, first order |
| Paper's full objective, $p=4$, $h\in(0.01,0.1)$, RK4 scaling baseline | 0.75–0.94 | about 400–600 times worse, first order |
| Paper's full objective, reachable $p=3$, RK3 scaling baseline | 0.44–0.92 | 530–801 times worse, first order |
| Any of these with `keep_order=3` | 0.25–1.00 | 0.34–1.00, third order |

With `keep_order=3` the error is never more than 0.2% above RK3's at any tested step. The unconstrained full-objective fits in the table stop at the iteration cap or when no step helps, and the reference says so.

The reference `train(..., keep_order=q)` is an addition to the paper's method. It holds the classical order conditions up to order $q$ (at most 4) exactly, to rounding, throughout the fit, and optimizes the loss along the set of tableaus that keep order $q$ on every ODE. Use it whenever you need the order at steps smaller than those trained on. It is preferable to large `order_weights`, which hold the conditions only approximately and lose the order at small enough steps. Its limits:

- Results depend on the starting tableau. Start from several classical tableaus with the stage count, such as RK3, Ralston's third-order method or RK4, and keep the best held-out result. The logits for given weights are $z_i=\log b_i$.
- With the paper's scaled loss, the loss can be far more sensitive across the constraint set than along it, beyond what the finite-difference Jacobian resolves. The fit then stops early and says it did not converge, as for some fits in `verify/check_order_target.py`. Its tableau still keeps order $q$ and is usable, but other starts may do better.
- Keep the states at ordinary magnitudes by nondimensionalizing them. Eq. (16) mixes derivatives of different orders, so the fitted tableau depends on the units.

After training, the reference warns heuristically when the fitted tableau matches a derivative order up to $\min(p,\text{reachable order})$ only approximately on the training tasks. This means a relative derivative error above $10^{-8}$. It checks up to the reachable order when the Taylor term is off. It also warns when the fit did not converge. `order_residuals` reports the residual of each order relative to the size of the derivative. These warnings do not replace measurements. In every case, compare held-out rollouts with a classical tableau of the same stage count, including steps smaller than the training range. Keep the classical tableau unless the fitted one is better.

**Order and the two-stage reproduction.** Softmax imposes the first-order condition. The penalty encourages local derivative matching on the sampled family. Exact matching through derivative $p$ across the relevant states yields local error $O(h^{p+1})$ and, on stable finite-time rollouts, global error $O(h^p)$. Small residuals can still cause lower-order terms to dominate at small $h$. Generic order two requires $b^T c=1/2$ with $c=A\mathbf1$. Generic order three also requires $\sum_i b_i c_i^2=1/3$ and $b^T A c=1/6$.

For $f(y)=-a y^2$, $a>0$, the paper samples $a$ uniformly in $(0.1,0.5)$ and $y_0$ uniformly in $(1,3)$ (Eq. (18)). Section 4.3 obtains special conditions $2a_{21}b_2=1$ and $a_{21}^2 b_2=1$, along with $b_1+b_2=1$ (Eq. (23)). They give $a_{21}=2$, $b=(3/4,1/4)$ (Eq. (24)). This tableau is third order on that family and second order on general smooth ODEs. Heun is the same-stage comparison in Fig. 4, with $a_{21}=1$, $b=(1/2,1/2)$ (Eq. (25)). The square example only activates the Taylor penalty, so it needs neither finite-step targets nor a scaling baseline.

Eq. (11) also implies that every three-stage explicit tableau with exact scalar linear order three has the same amplification polynomial as RK3. Its cubic coefficient is $1/6$. From the rounded linear-family weights in Table 1, the fitted cubic coefficient is about $0.1657$. This calculation is consistent with the change in slope at small steps in Fig. 2a. Check both the polynomial coefficients and observed convergence slope.

## 5. Parameters

| Parameter | How to choose it |
| --- | --- |
| Stage count $s$ | Set the RHS evaluation budget per step. Compare against a classical method with the same budget. |
| Step size $h$ | Train and validate at the intended step size or over the intended range. Include endpoints and a smaller-step sweep. |
| Order target $p$ and loss weights | Set $p$ from the desired accuracy and test if the family and stage count can achieve it. Whenever you need the order at steps smaller than those trained on, use `keep_order` with that order: with the finite-step term always, and with the Taylor term alone when $p$ exceeds the order the stages reach in general. Check `order_residuals` and the slope at small steps after training. The illustrative square fit uses $p=3$ and the Taylor penalty alone. |
| Training states and targets | Use states and rates with the deployment scales, including trajectory regions that are hard to integrate. Check target accuracy and the resolution of the baseline error. |

## 6. Applying it to your own code

Train against several tasks and use the resulting coefficients as constants. Store the stage rows in evaluation order and keep the start state unchanged while forming all stages. The compact representation has row lengths $0,1,\ldots,s-1$. In a nonautonomous problem, augment the state with $t'=1$ (§2.1) so that stage times are $t+c_i h$. Include the time distribution in training and validation.

Differentiate through the stage evaluations during training. The reference `train` accepts a batch of `rhs` and `state` pairs. For an active finite-step term, each task also supplies `h`, `target` and `baseline`. It takes compact initial rows and output logits, computes both derivative sets, and returns `(A, b, loss)`. It uses damped Gauss–Newton with finite differences in coefficient parameter space. Without `max_iters` it iterates until the gradient (along the constraint set under `keep_order`) is small relative to the loss, up to `MAX_ITERS` (2000), and warns if it stops before that. `max_iters` sets another cap, and `0` only evaluates the starting tableau. The keyword `keep_order` holds classical order conditions exactly by constrained Gauss–Newton steps, and `order_weights` scales each derivative order's residual. A `RuntimeWarning` reports derivative orders up to $\min(p,\text{reachable order})$ that the fitted tableau matches only approximately on the training tasks. The time-step derivatives come from series arithmetic at zero. For smooth Python RHSs the series supports arithmetic, division with a nonzero constant denominator, integer powers, and the supplied `sin`, `cos` and `exp` functions. Use equivalent differentiable primitives in your own numerical framework for other operations.

At inference only the RHS and the tableau are needed. Export at full precision and check consistency and order residuals after export.

When you write code using this method, add the comment `learned-rk v0.1.0, Guo et al. 2022`.

## 7. Verification

1. **Check your implementation.** Keep `checks/check_port.py` beside `checks/cases.json`. In your working directory expose `step`, `objective`, `rk_derivatives`, `flow_derivatives`, `train` and `order_conditions` from `port_adapter.py` and run `python /path/to/learned-rk/checks/check_port.py`. Show the user the output. The JSON specifies the same interfaces for other languages. It tests the fixed step, loss, both derivative calculations, the classical order conditions, initial softmax, a small fit with both terms active and a `keep_order=3` fit on Duffing oscillators. A port that fits without the constraint and projects at the end fails that case. Because the `keep_order` optimum is a flat valley, that case compares the loss and checks the conditions of your tableau, not its coefficients. The fit case leaves the iteration count to your optimizer and checks only the result: Gauss–Newton needs tens of iterations, Adam can need thousands. Validate coefficient and loss tolerances in double precision.
2. **Check your problem.** Compare held-out rollout errors at the same $h$ and stage count, including difficult tasks and the tails of the distribution. Step halve at a common physical end time and inspect the trajectory errors and observed order. For linear decay $y'=\lambda y$, check that the amplification factor satisfies $|1+z b^T(I-zA)^{-1}\mathbf 1|\leq1$ over the relevant $z=h\lambda$. Validate representative nonlinear rollouts as well. Use a classical baseline when the fitted tableau misses the required error or stability target.

## 8. Failure signatures

| Symptom | Likely cause |
| --- | --- |
| Constant RHS drifts at the wrong rate | Output weights do not sum to one, or $h$ was applied incorrectly. |
| Loss explodes or becomes nonfinite for tiny steps | The baseline error is zero or indistinguishable from roundoff. |
| Good finite-step fit and a lower slope under refinement | The Taylor derivatives were mismatched or the penalty only made their residuals small on training samples. |
| Training lowered the loss, but the fitted tableau is worse than the classical one of the same stage count at small steps, and its slope dropped | No order was held exactly. The finite-step term rewards only the training steps, and with an out-of-reach target the unweighted penalty trades the lower orders for the top one. The reference warns about it. Use `keep_order`. |
| The RHS raises `TypeError: must be real number, not Series` | The RHS calls a function that does not accept the series used for the $h$ derivatives, such as `math.sin`. Use the series `sin`, `cos` and `exp` from `reference/taylor_series.py`, or your framework's differentiable functions. |
| Error or growth spikes on new tasks or larger steps | The deployment family or stability regime differs from the validated range. |
| A transferred tableau gives more error at the same cost | The cancellation that helped on the training family can increase the leading error on other RHSs. For $y'=\sin y$, the square-family tableau gave about 3.54 times Heun's error at the same stage count. |
| One-step error looks good but trajectories drift | Visited states or the rollout horizon are poorly represented in training and validation. |

## 9. Files and commands

Run from this skill folder. All shipped scripts use the standard library.

| File | Use |
| --- | --- |
| `reference/learned_rk.py` | Explicit step, batch objective and closed-form square-family comparison. |
| `reference/train_rk.py`, `reference/taylor_series.py` | Training from raw tasks, derivatives at zero and series operations. |
| `examples/fit_square.py` | `uv run --offline examples/fit_square.py` uses the general trainer to fit the Taylor penalty and compares two new tasks with Heun. Expected output is in `examples/fit_square.expected.txt`. |
| `checks/cases.json`, `checks/check_port.py` | Fixed cases and property checks for your port. Run the checker from your adapter's directory as above. |
| `checks/make_cases.py` | `uv run --offline checks/make_cases.py` prints the fixtures generated from the reference. |
| `verify/check_cases.py` | `uv run --offline verify/check_cases.py` checks fixture freshness, an independent optimum and deliberate porting errors. |
| `verify/check_paper.py` | `uv run --offline verify/check_paper.py` checks the closed-form tableau from Eqs. (23)–(24) and the order shown in Fig. 4 on new tasks. It also checks transfer to linear decay and a nonlinear sine RHS. |
| `verify/check_order_target.py` | `uv run --offline verify/check_order_target.py` shows, on a pendulum family, the Taylor term only with $p=4$ and the paper's full objective with $p=4$ and with the reachable $p=3$. The fits without `keep_order` warn and lose order at small steps. With `keep_order=3`, each fit keeps third order and stays within 0.2% of RK3's error or below at every tested step, from RK3 or from a random start. A four-stage `keep_order=4` fit from RK4 moves away from RK4 and lowers the loss. |

The square-family scripts check the reported tableau and its accuracy. The example uses the reference optimizer, and the paper used Adam. In the authors' research code listed in `meta.yaml`, the checkpoint at `results/Nonlinear/rk2_taylor3.h5` stores a stage kernel and two output logits. Reading the kernel and applying softmax to the logits gave the Eq. (24) tableau within $1.4\times10^{-15}$ per coefficient.

## 10. Sources

- Y. Guo, F. Dietrich, T. Bertalan, D. T. Doncevic, M. Dahmen, I. G. Kevrekidis and Q. Li. *Personalized Algorithm Generation: A Case Study in Learning ODE Integrators*. SIAM Journal on Scientific Computing 44(4), A1911–A1933 (2022). [Published article](https://doi.org/10.1137/21M1418629)
- The open manuscript supplies the equation, section and figure numbering used here. [arXiv:2105.01303v3](https://arxiv.org/abs/2105.01303v3)
- Earlier neural approaches fitted RK coefficients for targeted IVPs. [Tsitouras 2002](https://doi.org/10.1109/72.977309), [Anastassi 2014](https://arxiv.org/abs/1106.1194), [Dehghanpour et al. 2015](https://doi.org/10.14419/jacst.v4i1.4365)
- Earlier classical RK design includes Fehlberg and Dormand–Prince. Optimal deterministic algorithm generation addresses the broader problem of optimizing a parameterized algorithm. [Fehlberg 1964](https://doi.org/10.1002/zamm.19640441310), [Dormand & Prince 1980](https://doi.org/10.1016/0771-050X(80)90013-3), [Mitsos et al. 2018](https://doi.org/10.1007/s10898-018-0611-8)

```bibtex
@article{guo2022personalized,
  author = {Guo, Yue and Dietrich, Felix and Bertalan, Tom and Doncevic, Danimir T. and Dahmen, Manuel and Kevrekidis, Ioannis G. and Li, Qianxiao},
  title = {Personalized Algorithm Generation: A Case Study in Learning {ODE} Integrators},
  journal = {SIAM Journal on Scientific Computing},
  year = {2022},
  volume = {44},
  number = {4},
  pages = {A1911--A1933},
  doi = {10.1137/21M1418629},
}
```
