# Checking a gradient

Channel: release; package: 2.2.0; source: 084b5032b7d014f12b65b4b947cf61a840970bf4

Page: https://remilab.ai/rfx/check/gradients/
Source: https://github.com/bk-squared/rfx/blob/084b5032b7d014f12b65b4b947cf61a840970bf4/docs/public/check/gradients.mdx

A gradient from `forward()` is the exact derivative of the run you set up. If
the run ends while a resonance is still ringing, every frequency of the result
keeps a leftover term whose phase grows with the simulation time T. A
parameter that moves the resonance turns that phase, and the turn enters the
derivative multiplied by T while the term stays small in the value. The value
can be converged while its gradient is still more than 10 % off.
[Simulation time for gradients](https://remilab.ai/rfx/check/gradient-simulation-time/) gives
how long the run must be, in decay times of the slowest mode.

The [settling check](https://remilab.ai/rfx/check/simulation-time/) is a statement about the
value and does not cover this. Neither does agreement between automatic
differentiation and finite differences: both differentiate the same run. The
check that sees it takes the same gradient from a longer run. Run it once for
each new setup before you optimize, and again for any gradient you report.

## Check a gradient from a longer run

The model is the one on the [Simulation time](https://remilab.ai/rfx/check/simulation-time/)
page: a lossy slab between a 50 Ω lumped port and a probe. The parameter is the
slab's permittivity, and the objective is the power the probe sees at three
frequencies. The objective takes the number of time steps as its second
argument, because the check runs it twice:

```python
import jax
import jax.numpy as jnp
from rfx import Box, GaussianPulse, Simulation, gradient_record_length_witness

sim = Simulation(freq_max=4e9, domain=(0.06, 0.05, 0.04), dx=2e-3,
                 boundary="cpml", cpml_layers=8)
sim.add_material("slab", eps_r=4.0, sigma=0.01)
sim.add(Box((0.024, 0.019, 0.014), (0.036, 0.031, 0.026)), material="slab")
sim.add_port((0.018, 0.025, 0.020), "ez", impedance=50.0,
             waveform=GaussianPulse(f0=3e9, bandwidth=0.8))
sim.add_probe((0.044, 0.025, 0.020), "ez")

grid = sim.freeze_mesh()
lo = grid.position_to_index((0.024, 0.019, 0.014))
hi = grid.position_to_index((0.036, 0.031, 0.026))
freqs = jnp.array([2.5e9, 3.0e9, 3.5e9])

def objective(eps_slab, n_steps):
    eps = jnp.ones(grid.shape).at[lo[0]:hi[0], lo[1]:hi[1], lo[2]:hi[2]].set(eps_slab)
    out = sim.forward(eps_override=eps, n_steps=n_steps, skip_preflight=True)
    t = jnp.arange(n_steps) * grid.dt
    phasor = jnp.exp(-2j * jnp.pi * freqs[:, None] * t) @ out.time_series[:, 0] * grid.dt
    return jnp.abs(phasor) ** 2

for n in (200, 300, 400):
    check = gradient_record_length_witness(objective, 4.0, n, tol=0.05)
    print(check.summary())
```

```text
gradient record-length witness FAIL: 200 -> 400 steps moved the gradient by 5.77% in bin 1 (tol 5.00%), direction cos 1.0000, the value by 4.170%
gradient record-length witness PASS: 300 -> 600 steps moved the gradient by 0.44% in bin 1 (tol 5.00%), direction cos 1.0000, the value by 0.042%
gradient record-length witness PASS: 400 -> 800 steps moved the gradient by 0.37% in bin 2 (tol 5.00%), direction cos 1.0000, the value by 0.018%
```

At 200 steps the source has not ended inside the run (the settling check on
the [Simulation time](https://remilab.ai/rfx/check/simulation-time/) page says
`undetermined`), and doubling the run moves both the value, by 4.2 %, and the
gradient, by 5.8 %. From 300 steps on the gradient moves by less than 0.5 %,
inside the 5 % tolerance chosen here, and its direction does not turn (cosine
1.0000). This gradient is usable from 300 steps on.

The slab is lossy and rings out within the pulse, so its gradient settles as
soon as its value does. A resonator does not: in the cavity under
[Where it is tested](#where-it-is-tested), a run that passes the settling check has its power
converged to 0.4 % while its gradient is still more than 10 % away. Run the
check on every new setup, and expect it to matter most where the structure
rings.

What to pass and read:

- `tol` is required and has no default. The right tolerance depends on the
  structure's Q, on how far the parameter moves a resonance and on what the
  gradient is for. State the tolerance you chose.
- `factor` (default 2) is the ratio of the two simulation times. The check only
  sees ringing that the longer run resolves: a run too short by more than
  `factor` can pass, because both runs carry a similar leftover. That is why
  the page reads it over three simulation times.
- `check.passed` and `check.worst` give the result. `check.rel_by_bin` gives it
  per frequency, `check.cosine_by_bin` says whether the direction of the
  gradient turned (below 1) or only its length changed (1),
  `check.worst_value_rel_change` shows the value's change beside it.
- The objective may return a scalar or one value per frequency, real or
  complex. Parameters may be any JAX tree of real floating-point leaves.
- The cost is two differentiated runs, one `factor` times longer, and a second
  compilation.

## Compare with finite differences

Compare the automatic-differentiation gradient with a central difference at the
same simulation time:

```python
n, h = 400, 0.1
ad = jax.jacfwd(objective)(4.0, n)
fd = (objective(4.0 + h, n) - objective(4.0 - h, n)) / (2 * h)
print(jnp.abs(ad - fd) / jnp.abs(fd))
```

```text
[5.2978587e-04 7.6487151e-05 2.3633518e-04]
```

The two agree within 0.06 % at each frequency. The printed values change between CPUs. rfx computes in float32 by
default, and an objective summed over hundreds of time steps carries rounding
well above float32's own precision. Choose `h` so the change of the objective,
about 2 h |dL/dp|, is far above that rounding: a smaller `h` is not more
accurate. A disagreement here points at the objective or the step `h`,
not at the simulation time.

A finite-difference check can also pass on an objective that measures nothing:
when the probe never sees the reflection during the run, or sits in the
absorber, both sides agree on a gradient of numerical noise. Compare the size
of the objective with what the physics leads you to expect.

## Gradients through tail extrapolation

With `forward(..., ringdown=RingdownSpec())` the completed S-parameters
(`out.ringdown.s_params`, see
[tail extrapolation](https://remilab.ai/rfx/check/simulation-time/#tail-extrapolation-by-matrix-pencil))
are differentiable, and their gradient has its own check: the same gradient
through the completion fitted on a window that starts twice as early
(`out.ringdown.s_params_long`). One forward pass gives both gradients:

```text
import jax
from rfx.ringdown import RingdownSpec, gradient_witness

def both(p):
    out = sim.forward(eps_override=p, n_steps=n, port_s11_freqs=freqs,
                      ringdown=RingdownSpec())
    return (loss(out.ringdown.s_params), loss(out.ringdown.s_params_long)), out.ringdown

(l, l_long), pullback, rd = jax.vjp(both, p, has_aux=True)
(g,) = pullback((1.0, 0.0))
(g_long,) = pullback((0.0, 1.0))
check = gradient_witness(g, g_long, ringdown=rd)
print(check.ok, check.value)
```

The check passes when, for every parameter leaf, the largest difference
between the two gradients is at most 1 % of that leaf's largest gradient
(`bar=1e-2`). When the gradient has a frequency axis, pass `bin_axis=` and only
the frequencies the objective reads, so a near-zero frequency at the band edge
does not decide the result. When the source is still on in the earlier window
or a completion failed, the check is not formed: `check.ok` is False,
`check.value` is NaN and `check.note` says why. Then compare with the same
gradient from a run 1.5 to 2 times longer:
`gradient_witness(g, g_longer, against="longer_record")`.

On a weakly coupled high-Q resonator, add
`RingdownSpec(identification_probes=...)` with a probe inside the resonator. A
fit from the port alone can get the value right and the gradient of that
resonance wrong.

### Frequency and Q of one resonance, per cell

`out.ringdown.pole(f_target)` returns the frequency and 1/Q of one fitted pole,
as traced values. One reverse pass through them gives df/dεr or d(1/Q)/dσ in
every cell, where two forward runs per cell would otherwise be needed. The
example is a closed PEC box in vacuum with a uniform conductivity of
1.44e-5 S/m. A weak 10 kΩ wire port drives its lowest resonance. Two field
probes inside the box join the fit.

```python
import jax
import jax.numpy as jnp
import numpy as np
from rfx import GaussianPulse, Simulation
from rfx.ringdown import RingdownSpec

C0, EPS_0 = 299792458.0, 8.8541878128e-12
SIGMA, RECORD_S, dx = 1.44e-5, 7.62e-9, 1e-3
probes = (((0.0183, 0.0041, 0.0157), "ey"), ((0.0059, 0.0092, 0.0194), "ey"))

with jax.enable_x64():
    sim = Simulation(freq_max=15e9, domain=(0.0265, 0.0127, 0.0241), dx=dx,
                     boundary="pec", precision="float64", snap="declared")
    sim.add_port(position=(0.0071, (0.0127 - 3 * dx) / 2, 0.0063), component="ey",
                 extent=3 * dx, impedance=10e3,
                 waveform=GaussianPulse(f0=8.4e9, bandwidth=0.8))
    grid = sim.freeze_mesh()
    a, _, d = [(n - 1) * dx for n in grid.shape]   # the box the mesh built
    target = C0 / 2 * np.hypot(1 / a, 1 / d)       # lowest mode, closed form
    spec = RingdownSpec(freq_max=15e9, identification_probes=probes)

    def poles(eps, sigma):
        out = sim.forward(eps_override=eps, sigma_override=sigma,
                          n_steps=round(RECORD_S / grid.dt),
                          port_s11_freqs=np.linspace(7e9, 10e9, 41),
                          ringdown=spec, skip_preflight=True)
        return out.ringdown.pole(target), out.ringdown

    (f, inv_q), pullback, rd = jax.vjp(
        poles, jnp.ones(grid.shape), jnp.full(grid.shape, SIGMA), has_aux=True)
    df_deps, _ = pullback((1.0, 0.0))        # df/deps_r per cell, Hz
    _, dinvq_dsigma = pullback((0.0, 1.0))   # d(1/Q)/dsigma per cell, m/S

    theta = np.pi * float(f) * grid.dt
    sum_sigma = float(jnp.sum(dinvq_dsigma))
    sum_eps = float(jnp.sum(df_deps))
    print(f"f = {float(f) / 1e9:.4f} GHz, Q = {1 / float(inv_q):.0f}")
    print(f"r_sigma = {sum_sigma * 2 * np.pi * float(f) * EPS_0 - 1:.1e}")
    print(f"r_eps = {sum_eps / (-float(f) / 2 * np.tan(theta) / theta) - 1:.1e}")
```

```text
f = 8.3544 GHz, Q = 3675
r_sigma = -2.5e-05
r_eps = -3.1e-05
```

The sum over all cells is the derivative for a uniform change of σ or εr, and
for a box filled uniformly with vacuum (εr = 1, the only fill measured) that
derivative has a closed form:

- Σ d(1/Q)/dσ = 1/(ω ε₀), with ω = 2πf and f the fitted frequency;
- Σ df/dεr = −(f/2)·tan θ/θ, with θ = πf·dt the Yee time-step correction.

`r_sigma` and `r_eps` are the relative differences from these two sums. Measured
in float64 on the CPU, each mesh with the box it realized (record kept with the
project):

| cell | f (GHz) | Q | r_sigma | r_eps |
|---|---|---|---|---|
| 1.0 mm | 8.354 | 3675 | −2.5e-5 | −3.1e-5 |
| 0.75 mm | 8.461 | 5943 | −1.9e-5 | −3.5e-5 |
| 0.5 mm | 8.426 | 9770 | −6.8e-6 | +3.7e-5 |

The largest difference is 3.7e-5, and it stays at a few 1e-5 on all three meshes.
This is the validated case: this box, its lowest resonance, a uniform mesh and
float64. The 1.0 mm case runs in the test suite
(`tests/oracle/test_traced_pole_output.py`). The sums test the total only; no
closed form tests how the sensitivity is spread over the cells.

To check a pole gradient, differentiate `pole(target)` and
`pole(target, window="long")` from one `forward()` call and pass
`pole_target=target` to `gradient_witness`:
`gradient_witness(g, g_long, ringdown=rd, pole_target=target)`. On the 0.5 mm
box above it was judged, at 3.0e-4 for f and 5.4e-4 for 1/Q against the bar
of 1e-2.

Limits:

- **No unique pole gives NaN.** `pole()` selects the one completed, decaying,
  positive-frequency pole within 1/(main window length) of `f_target`. With none
  or several there, or a failed fit, both values and their gradients are NaN.
  `rfx.ringdown.pole_selection_reason` gives the reason on the host.
- **No unique pole cannot be judged.** With `pole_target`, `gradient_witness`
  needs a unique pole in both windows. Otherwise `check.judged` and `check.ok`
  are False, `check.value` is NaN and `check.note` starts `cannot judge:`.
- **The two windows are matched by frequency only.** The match assumes isolated
  neighbours. `gradient_witness` is the check for a wrong match.
- **Plain and `jax.jit` gradients agree once the witnesses pass.** On the 1.0 mm box above the pole
  gradients agree to 1.1e-12 and the gradient of `sum |S|^2` to 2.7e-11. On a short lossy 600-step test box the gradient of `sum |S|^2`
  differs by up to 1.7e-2, and the pole outputs differ more; that record is too short, and both
  `report.ok` and the early-start `gradient_witness` reject it. From 1200 steps on that box, where both pass, the
  two agree within 5.5e-6. Read a gradient through `forward(ringdown=...)` only when its witnesses pass.

## How the checks work

**The gradient check from a longer run** (`gradient_record_length_witness`). Per frequency, the
relative change of the whole gradient vector, over every element of every
parameter: ‖g_long − g‖ / ‖g_long‖. There is no floor in it, so an element with
almost no sensitivity cannot decide it. `grad_rel_change` holds the
per-element changes, floored at `floor_frac` of the largest gradient; use it to
find where a failed check sits, not as the result. The number depends on how
you parameterize, so check the parameters you optimize.

**The tail-extrapolation check** (`rfx.ringdown.gradient_witness`). Per
parameter leaf, the largest difference between the two gradients over that
leaf's largest gradient, against 1 %. A NaN in either gradient fails it.

## Inputs rfx refuses

| Input | What happens | Instead |
|---|---|---|
| a complex parameter leaf in `gradient_record_length_witness` | `ValueError` with the reason | pass the real and imaginary parts as separate real leaves |
| an integer or boolean parameter leaf | `ValueError`: it carries no gradient | cast it to a float |
| `gradient_record_length_witness` without `tol` | `TypeError` | state the tolerance |
| `forward(ringdown=...)` with `distributed=True` | refused | run on one device |
| `forward(ringdown=...)` with `emit_time_series=False` | refused: the port signals are recorded as probe series | keep the time series |
| `forward(ringdown=...)` without `port_s11_freqs=`, on either mesh | refused | pass the frequencies |
| a gradient with respect to a declared shape's size or position (a sphere radius, a box corner) | `NotImplementedError` naming the supported routes, on `run()` and `forward()` | differentiate through material overrides (`eps_override`) or a design region |
| `forward(ringdown=...)` with more than one wire port on a uniform mesh | refused | use a graded mesh |
| `forward(ringdown=...)` or `run(ringdown=...)` under `jax.grad`, `jax.jvp`, `jax.vmap` or `jax.jit` with a traced drive waveform, or on a traced graded mesh without `dt=` | refused: the drive's off time inside the fit window cannot be judged | declare the waveform with concrete values (S does not depend on the drive's amplitude), or pin `dt=` |
| `gradient_witness(..., against="early_start")` without `ringdown=` | `TypeError` | pass the call's `out.ringdown` |
| `gradient_witness(..., pole_target=..., against="longer_record")` without a result pair | needs `ringdown=(res, res_longer)` | pass each record's concrete, unbatched `out.ringdown`, in gradient order |
| `out.ringdown.pole(f_target, window=...)` with a window other than `"main"` or `"long"` | `ValueError` | pass one of the two |
| `out.ringdown.pole(...)` on a result batched by `jax.vmap` | `ValueError` naming the shape | take one element first: `jax.tree_util.tree_map(lambda a: a[i], result)` |

The refusals of `run(ringdown=...)` that concern the model (port kinds, solver
paths, the source in the fit window) on the
[Simulation time](https://remilab.ai/rfx/check/simulation-time/#inputs-rfx-refuses)
page apply to `forward(ringdown=...)` too. Like `run()`, `forward(ringdown=...)`
needs a driven wire port, which the slab model above does not have.

## Where it is tested

- On a lossy-filled PEC cavity in the test suite (Q about 20 near 7 GHz), a
  1600-step run passes the −40 dB settling check and its power is converged to
  0.4 %, while the gradient with respect to the fill's permittivity is still
  more than 10 % away from its converged value; doubling the run brings it
  below 2.5 %
  (`tests/unit/autodiff/test_gradient_record_length_witness.py::test_cavity_gradient_needs_a_longer_record_than_its_value`).
- On a metal box filled with εr = 2.2 and fed by a wire port, the gradient through tail extrapolation from
  a 1500-step run is within 1 % of the one from a 4000-step run, while the plain
  gradient from the same 1500 steps is more than 50 % off; the
  tail-extrapolation check reads the actual error within a factor of 2 at 600
  and 800 steps and passes at 1500
  (`tests/unit/sparams/test_ringdown_forward.py`).

## See also

- [Autodiff and adjoint background](https://remilab.ai/rfx/design/gradients/): what `forward()`
  can differentiate.
- [Simulation time for gradients](https://remilab.ai/rfx/check/gradient-simulation-time/): how
  long a gradient must run, and when it changes a design.
- [Is the run long enough?](https://remilab.ai/rfx/check/simulation-time/): the settling check
  for the value.
- [When does a result agree with a reference?](https://remilab.ai/rfx/check/agreement/).
