# Torch Integration The optional `jcmsuite.torch` namespace adapts ordinary JCMsuite solves for PyTorch objectives. Use this namespace when you need to include solver results in a PyTorch calculation. Ordinary `jcmsuite` solves do not change. ```{admonition} Experimental feature :class: warning The `jcmsuite.torch` integration is experimental. Its API and behavior can change in future releases. Do not depend on its current interface for production workflows without testing each package update. ``` ```{admonition} Solver derivative support :class: note JCMsuite computes solver derivatives only for `Scattering` projects. `PropagatingMode` and `ResonanceMode` projects do not provide these derivatives. The Torch adapter needs solver derivatives to connect result tensors to gradient-enabled {term}`project keys`. It cannot differentiate eigenvalues from mode projects through these bindings. ``` ## Install PyTorch Install the optional Torch extra to use the adapter: ```bash python -m pip install "jcmsuite[torch]" ``` The `jcmsuite` package does not install PyTorch as a required dependency. Importing `jcmsuite` and using ordinary solves does not require PyTorch. The adapter loads PyTorch when you call {func}`solve `. ## Run a Solve Set up the JCM input files as shown in [Derivative Setup](setup.md). This example declares a height derivative in the {term}`project` template. ```{literalinclude} ../../demos/documentation_tutorials/derivatives/torch/real_derivative/layout.jcmt :language: jcm :lines: 5-8 ``` Pass Torch tensors as {term}`project key ` values to {func}`solve `. Set `requires_grad=True` for inputs that must receive gradients. {term}`Project key ` names and solver derivative labels can differ. ```{literalinclude} ../../demos/documentation_tutorials/derivatives/torch/real_derivative/run.py :language: python :lines: 6-24 ``` ## Connect an Input to a Derivative The solver computes a derivative for a declared parameter. A binding connects that derivative to a Torch input. In `key_derivative_map`, put the {term}`project key ` name on the left and the solver derivative binding on the right: ```python width = torch.tensor(31.0, requires_grad=True) key_derivative_map = {"width": RealDerivative("width_parameter")} ``` Use {class}`RealDerivative ` to bind a real tensor to one solver derivative. Use {class}`ComplexDerivative ` to bind a complex tensor to separate solver derivatives for its real and imaginary input components. Add one binding for each {term}`project key ` whose Torch tensor has `requires_grad=True`. The {term}`project key ` name and the solver derivative label can differ. The adapter raises an error when a binding is missing, unknown, duplicated, or invalid. Fixed Python values, NumPy values, integers, booleans, and tensors without gradients do not need a binding. ## Compute Gradients The postprocess data returned by {func}`jcmsuite.torch.solve` contains Torch tensors. Use `torch.autograd.grad()` or `.backward()` for a scalar objective. The following examples show the common derivatives with respect to real and complex input parameters. ### Real Input Parameters For a real {term}`project key `, use {class}`RealDerivative ` to connect the {term}`project key ` to a solver derivative. The result tensor remains connected to the Torch input. After the solve, you can use `torch.autograd.grad()` or `.backward()` on a scalar result: ```{literalinclude} ../../demos/documentation_tutorials/derivatives/torch/real_derivative/run.py :language: python :lines: 26-36 ``` ### Complex Input Parameters For a complex {term}`project key `, define separate solver derivatives for the real and imaginary input components: ```{literalinclude} ../../demos/documentation_tutorials/derivatives/torch/complex_derivative/materials.jcmt :language: jcm :lines: 1-14 ``` Bind both solver derivatives to the same {term}`project key ` with {class}`ComplexDerivative `: ```{literalinclude} ../../demos/documentation_tutorials/derivatives/torch/complex_derivative/run.py :language: python :lines: 6-27 ``` Finally, compute the derivative of the real or imaginary part of the result tensor with `torch.autograd.grad()` or `.backward()`. The returned gradient is a complex tensor. ```{literalinclude} ../../demos/documentation_tutorials/derivatives/torch/complex_derivative/run.py :language: python :lines: 29-39 ``` (complex-input-convention)= ### Complex Input Convention The solver returns one complex derivative for each real coordinate of a complex {term}`project key `. Let the {term}`project key ` be $$ z = x + i y $$ and let the complex result be $$ F(z) = u(x,y) + i v(x,y). $$ The solver derivatives are the complex values $$ F_x = \frac{\partial F}{\partial x} = \frac{\partial u}{\partial x} + i\frac{\partial v}{\partial x}, \qquad F_y = \frac{\partial F}{\partial y} = \frac{\partial u}{\partial y} + i\frac{\partial v}{\partial y}. $$ PyTorch packs the real and imaginary input directions in one complex tensor. The packed gradients of the real and imaginary result components are $$ \operatorname{grad}(u,z) = \frac{\partial u}{\partial x} + i\frac{\partial u}{\partial y} = \operatorname{Re}(F_x) + i\operatorname{Re}(F_y), $$ $$ \operatorname{grad}(v,z) = \frac{\partial v}{\partial x} + i\frac{\partial v}{\partial y} = \operatorname{Im}(F_x) + i\operatorname{Im}(F_y). $$ These two PyTorch gradients contain the rows of the full real Jacobian: $$ J_{\mathbb{R}} = \begin{pmatrix} \dfrac{\partial u}{\partial x} & \dfrac{\partial u}{\partial y} \\ \dfrac{\partial v}{\partial x} & \dfrac{\partial v}{\partial y} \end{pmatrix} = \begin{pmatrix} \operatorname{Re}(F_x) & \operatorname{Re}(F_y) \\ \operatorname{Im}(F_x) & \operatorname{Im}(F_y) \end{pmatrix}. $$ This coordinate packing does not assume that the field is holomorphic. The solver labels identify independent real-coordinate partial derivatives, and ordinary complex autograd remains supported. When `Order = 2` data is available, the adapter uses those real-coordinate labels to connect the complete Hessian for real, complex, or mixed scalar inputs. It does not infer missing entries from holomorphic identities. The following example shows the mapping. The ordinary result exposes `F_x` and `F_y` separately. The {class}`ComplexDerivative ` binding connects them to `permittivity`. ```python ordinary_result = results.untorch() ordinary_data = ordinary_result.postprocesses[0].to_dict() F_x = ordinary_data["d_permittivity_real"]["ElectricFieldStrength"][0][0][0] # complex F_y = ordinary_data["d_permittivity_imag"]["ElectricFieldStrength"][0][0][0] # complex field = results.postprocesses[0].to_dict()["ElectricFieldStrength"][0][0][0] torch_grad_u = torch.autograd.grad(field.real, permittivity)[0] # real(F_x) + 1j * real(F_y) torch_grad_v = torch.autograd.grad(field.imag, permittivity)[0] # imag(F_x) + 1j * imag(F_y) ``` ## Batches And Bundles ### Batch Results Pass {term}`batched project keys` to run a batch. Use one derivative map for the {term}`project`. A {class}`TorchBatchSolveResult ` remains split by its original batch entry. ```{literalinclude} ../../demos/documentation_tutorials/derivatives/torch/batch/run.py :language: python :lines: 8-24 ``` To create a stacked tensor, iterate over the batch entries. ```{literalinclude} ../../demos/documentation_tutorials/derivatives/torch/batch/run.py :language: python :lines: 26-31 ``` ### Ordered Project Bundles Derivative maps for an {term}`ordered project bundle` follow {term}`project` order: ```{literalinclude} ../../demos/documentation_tutorials/derivatives/torch/bundle/run.py :language: python :lines: 8-25 ``` Pass one derivative map per {term}`project` in bundle order. An empty map is an explicit opt-out for an entry. A {term}`project key ` cannot be shared between entries in an {term}`ordered project bundle`. Every tensor with `requires_grad=True` must be accounted for once and only once for the entire solve call. ## Export Result Data Use {meth}`to_dict() ` on a Torch-aware postprocess record to export numeric values as `torch.Tensor` objects. If a value has solver derivative data, its tensor stays connected to the bound Torch input. Other numeric values become detached tensors. Dictionary exports omit raw solver derivative branches. The adapter does not convert costs, headers, or other forwarded metadata automatically. Torch-aware records reject {meth}`to_df() ` and {meth}`to_xarray() ` with {class}`UnsupportedExportError `. Use {meth}`untorch() ` to access the ordinary result when you need DataFrame or xarray exports. ## Compute Second Derivatives Set `Order = 2` in the project. Existing {class}`RealDerivative ` and {class}`ComplexDerivative ` bindings are sufficient. Complex solver labels denote the real and imaginary input coordinates; the Hessian is assembled in real coordinates even when the result is complex. Use `create_graph=True` when the first gradient must itself be differentiated. Use `retain_graph=True` when another gradient calculation will reuse the same completed result graph. These options have separate purposes: `create_graph` records the gradient calculation, while `retain_graph` preserves the original graph after backward. PyTorch's normal graph-lifetime rules apply; retention is not automatic. For a real scalar objective, standard `torch.autograd.grad()` calls can assemble Hessian rows or compute a Hessian-vector product from one retained result. A Hessian-vector product uses a vector cotangent and does not require dense Hessian assembly. The adapter does not change the project or run another solve during autograd. Missing pairs are not treated as zero. Third-order solver derivatives and solve-backed `torch.func.hessian()` are not supported. Requests that require third-order solver derivatives raise an error. See the [numeric postprocess example](../tutorials/derivatives/torch/second_order_postprocess.md) for a Fourier objective and nested scattering derivatives. ## Dtype And Device Rules The adapter accepts these mixed differentiable input pairs: | Real input | Complex input | | ---------- | ------------- | | `float32` | `complex64` | | `float64` | `complex128` | All Torch inputs must use one device. The adapter rejects incompatible dtypes and devices. The supported differentiable {term}`project keys` are scalar Torch tensors. Tensor-valued {term}`project keys` are outside the current Torch derivative contract. Fixed Python and NumPy values can be used with supported differentiable tensors. Integer and boolean fixed {term}`project keys` can be used with either supported differentiable dtype pair. ## Backend Information The adapter attaches solver derivatives to PyTorch automatic differentiation. Result tensors support reverse-mode differentiation through `backward()`, `torch.autograd.grad()`, and `torch.func.vjp()`. They also support forward-mode differentiation through `torch.func.jvp()`. For a tensor output, `torch.func.vjp()` requires a cotangent tensor with the output shape. An all-ones cotangent returns the gradient of the sum of the output elements, not the complete Jacobian. ## Troubleshooting Use the following checks when a Torch solve or derivative lookup fails: - Install the optional `torch` dependency when the adapter reports that PyTorch is unavailable. - Add exactly one derivative binding for each gradient-enabled {term}`project key `. - Keep differentiable Torch inputs on one device and use the supported real or complex dtype pair. - Check that each bound solver derivative label is present in the result data. - Inspect the ordinary result with {meth}`untorch() ` when you need raw solver derivative data or ordinary result navigation. ## Next Steps - See the [Torch API reference](../reference/torch.md) for signatures and parameter types. ## Tutorials - [Differentiate structured result data](../tutorials/derivatives/torch/autograd_table.md). - [Check real and complex Torch gradients](../tutorials/derivatives/torch/gradcheck.md). - [Bind real derivatives](../tutorials/derivatives/torch/real_derivative.md). - [Bind complex derivatives](../tutorials/derivatives/torch/complex_derivative.md). - [Export Torch result data](../tutorials/derivatives/torch/table_export.md) and [check export limits](../tutorials/derivatives/torch/export_limits.md). - See all [Torch derivative tutorials](../tutorials/derivatives/torch/index.md), including derivative-binding validation examples.