12 — Differentiable Coupled Transport (Autodiff ↔ Finite-Difference Parity)¶
The coupled-transport solver advances plasma temperature, density and current-diffusion profiles together. Written in JAX, the whole forward chain is differentiable: the gradient of a control objective with respect to the actuator scales (heat power, particle rate, driven current) is obtained by reverse-mode automatic differentiation instead of finite differencing, which is what makes gradient-based scenario optimisation tractable.
This notebook drives the repository's tracked evidence generator for that capability. It rebuilds the differentiable-transport report and shows the central quantitative claim: the autodiff gradient matches a central finite-difference gradient of the same production forward model to a maximum relative error near $2\times10^{-8}$.
License: © 1996–2026 Miroslav Šotek. GNU AGPL-3.0-or-later (commercial licence available).
Run from a repository checkout. This notebook imports the repo-internal
validationpackage, which is not part of the PyPI wheel, so it is not a Colab notebook. Run it from a clone ofmainwith the project virtualenv. The APIs shown here ship after the 4.0.0 release.
Evidence boundary. The generator is fail-closed: it computes gates and a scientific projection and refuses to certify a mutated projection. It does not claim performance superiority or general transport differentiability — only the specific, bounded gradient-parity result below.
1 · Rebuild the tracked report¶
build_report() runs the differentiable forward model, computes the reverse-mode gradient of the
control objective, computes a central finite-difference gradient for comparison, and evaluates every
acceptance gate. It is side-effect free (it does not overwrite the tracked artifact).
import sys, json
from pathlib import Path
# Locate a repository checkout (this notebook lives in <repo>/examples).
try:
from validation import benchmark_torax_differentiable_transport as bench
except ModuleNotFoundError:
here = Path.cwd()
root = next((p for p in (here, *here.parents) if (p / "validation").is_dir()), None)
if root is None:
raise SystemExit(
"Run this notebook from a SCPN-FUSION-CORE checkout (the repo-internal "
"'validation' package is not shipped in the PyPI wheel)."
)
sys.path.insert(0, str(root))
from validation import benchmark_torax_differentiable_transport as bench
print("evidence generator:", bench.__name__)
evidence generator: validation.benchmark_torax_differentiable_transport
report = bench.build_report()
gm = report["gradient_metrics"]
contract = report["target_contract"]
labels = [n.replace("_scale", "").replace("_", " ") for n in contract["control_order"]]
print("status :", report["status"])
print("passes_thresholds :", report["passes_thresholds"])
print("runtime (s, cold) :", {k: round(v, 2) for k, v in report["runtime_seconds"].items()})
print()
print("acceptance gates:")
for gate, ok in report["gates"].items():
print(f" [{'PASS' if ok else 'FAIL'}] {gate}")
print()
print(f"max relative error (autodiff vs central FD): {gm['maximum_relative_error']:.3e}")
print()
print("claim boundary (honest by construction):")
print(" performance_superiority_claimed :",
report["performance_superiority_claimed"])
print(" general_transport_differentiability_claimed:",
report["general_transport_differentiability_claimed"])
# Rebuilt report must agree with the tracked artifact.
print("\ntracked-artifact freshness check:", bench.check_report() or "OK (in sync)")
WARNING:2026-08-29 20:30:32,426:jax._src.xla_bridge:864: An NVIDIA GPU may be present on this machine, but a CUDA-enabled jaxlib is not installed. Falling back to cpu.
status : differentiable_model_intersection_evaluated
passes_thresholds : True
runtime (s, cold) : {'differentiation_cold': 1.86, 'native_optimisation_cold': 1.82, 'torax_nominal_cold': 7.32}
acceptance gates:
[PASS] production_forward_replay
[PASS] finite_full_chain_gradients
[PASS] central_finite_difference
[PASS] perturbation_replay
[PASS] deterministic_optimisation
[PASS] optimisation_quality
[PASS] same_case_cost
max relative error (autodiff vs central FD): 2.184e-08
claim boundary (honest by construction):
performance_superiority_claimed : False
general_transport_differentiability_claimed: False
tracked-artifact freshness check: OK (in sync)
2 · Gradient parity, per actuator¶
The objective is differentiated with respect to three actuator scales — heat power, particle rate and driven current. The bars below are the per-component relative error between the autodiff gradient and the central finite-difference gradient; every component sits far below the acceptance threshold.
import numpy as np
import matplotlib.pyplot as plt
rel_err = np.abs(np.asarray(gm["relative_error"]))
fig, ax = plt.subplots(figsize=(6.2, 3.6))
bars = ax.bar(labels, rel_err, color="#38bdf8", edgecolor="#0b5", linewidth=0.6)
ax.set_yscale("log")
ax.axhline(gm["maximum_relative_error"], color="crimson", ls="--", lw=1,
label=f"max = {gm['maximum_relative_error']:.1e}")
ax.set_ylabel("relative error (autodiff vs central FD)")
ax.set_title("Reverse-mode gradient matches finite differences per actuator")
for b, v in zip(bars, rel_err):
ax.text(b.get_x() + b.get_width() / 2, v, f"{v:.1e}",
ha="center", va="bottom", fontsize=8)
ax.legend(fontsize=8); plt.tight_layout(); plt.show()
3 · Gradient-based control trajectory¶
Because the forward model is differentiable, a deterministic gradient descent drives the actuator scales from their initial values toward the target contract. The report records the full control history; each curve is one actuator scale over the optimisation iterations.
history = np.asarray(report["optimisation"]["control_history"])
target = np.asarray(contract["target_controls"])
fig, ax = plt.subplots(figsize=(6.2, 3.8))
colors = ["#38bdf8", "#f59e0b", "#a78bfa"]
for j, (lab, c) in enumerate(zip(labels, colors)):
ax.plot(history[:, j], color=c, marker="o", ms=3, lw=1.4, label=lab)
ax.axhline(target[j], color=c, ls=":", lw=1, alpha=0.7)
ax.set_xlabel("optimisation iteration")
ax.set_ylabel("actuator scale")
ax.set_title("Deterministic gradient descent toward the target contract\n(dotted = target)")
ax.legend(fontsize=8); plt.tight_layout(); plt.show()
What this shows — and what it does not¶
- Shown. The production coupled-transport forward model is end-to-end differentiable: its reverse-mode gradient reproduces a central finite-difference gradient of the same model to a maximum relative error near $2\times10^{-8}$, and that gradient drives a deterministic descent toward the target actuator contract. Every acceptance gate passes and the rebuilt report matches the tracked artifact byte-for-byte.
- Not claimed here. The generator explicitly sets
performance_superiority_claimed = Falseandgeneral_transport_differentiability_claimed = False: this is a bounded parity result on one tracked case, not a wall-clock or general-differentiability claim. Accepted parity status lives in the tracked report undervalidation/reports/torax_differentiable_transport.md.