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.

Experimental feature

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.

Solver derivative support

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 project keys. It cannot differentiate eigenvalues from mode projects through these bindings.

Install PyTorch

Install the optional Torch extra to use the adapter:

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 solve.

Run a Solve

Set up the JCM input files as shown in Derivative Setup. This example declares a height derivative in the project template.

DerivativeParameter {
  Name = "height"
  TreeEntry = "Layout2D/Objects/Line/Height"
}

Pass Torch tensors as project key values to solve. Set requires_grad=True for inputs that must receive gradients. Project key names and solver derivative labels can differ.

height = torch.tensor(
    55.0,
    dtype=torch.float64,
    requires_grad=True,
)

results = jcmsuite.torch.solve(
    "project.jcmp",
    keys={
        "h": height,
        "width": 31.0,
        "swa": 88.0,
        "radius": 8.0,
        "permittivity": 1.967 + 4.443j,
    },
    key_derivative_map={
        "h": RealDerivative("height"),
    },
)

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 project key name on the left and the solver derivative binding on the right:

width = torch.tensor(31.0, requires_grad=True)
key_derivative_map = {"width": RealDerivative("width_parameter")}

Use RealDerivative to bind a real tensor to one solver derivative. Use ComplexDerivative to bind a complex tensor to separate solver derivatives for its real and imaginary input components.

Add one binding for each project key whose Torch tensor has requires_grad=True. The 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 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 project key, use RealDerivative to connect the 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:

field = results.postprocesses[0].to_dict()["ElectricFieldStrength"][0][0][0]
real_torch_height_grad = torch.autograd.grad(
    field.real,
    height,
    retain_graph=True,
)[0]
imag_torch_height_grad = torch.autograd.grad(
    field.imag,
    height,
    retain_graph=True,
)[0]

Complex Input Parameters

For a complex project key, define separate solver derivatives for the real and imaginary input components:

DerivativeParameter {
  Name = "permittivity_real"
  TreeEntry {
    Path = "Material_3/RelPermittivity"
    Scaling = (1, 0)
  }
}
DerivativeParameter {
  Name = "permittivity_imag"
  TreeEntry {
    Path = "Material_3/RelPermittivity"
    Scaling = (0, 1)
  }
}

Bind both solver derivatives to the same project key with ComplexDerivative:

permittivity = torch.tensor(
    1.967 + 4.443j,
    dtype=torch.complex128,
    requires_grad=True,
)

results = jcmsuite.torch.solve(
    "project.jcmp",
    keys={
        "h": 55.0,
        "width": 31.0,
        "swa": 88.0,
        "radius": 8.0,
        "permittivity": permittivity,
    },
    key_derivative_map={
        "permittivity": ComplexDerivative(
            real="permittivity_real",
            imaginary="permittivity_imag",
        ),
    },
)

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.

field = results.postprocesses[0].to_dict()["ElectricFieldStrength"][0][0][0]
real_torch_permittivity_grad = torch.autograd.grad(
    field.real,
    permittivity,
    retain_graph=True,
)[0]
imag_torch_permittivity_grad = torch.autograd.grad(
    field.imag,
    permittivity,
    retain_graph=True,
)[0]

Complex Input Convention

The solver returns one complex derivative for each real coordinate of a complex project key. Let the 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 ComplexDerivative binding connects them to permittivity.

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 batched project keys to run a batch. Use one derivative map for the project. A TorchBatchSolveResult remains split by its original batch entry.

widths = torch.linspace(29.0, 33.0, 3, dtype=torch.float64, requires_grad=True)

results = jcmsuite.torch.solve(
    "project.jcmp",
    keys=[
        {
            "h": 55.0,
            "width": width,
            "swa": 88.0,
            "radius": 8.0,
            "permittivity": 1.967 + 4.443j,
        }
        for width in widths
    ],
    temporary=True,
    key_derivative_map={"width": RealDerivative("width_parameter")},
)

To create a stacked tensor, iterate over the batch entries.

intensities = [
    entry.result.postprocesses[0].to_dict()["ElectricFieldStrength"][0][0][0]
    for entry in results
]
stacked_intensity = torch.stack(intensities)
print(stacked_intensity.shape)

Ordered Project Bundles

Derivative maps for an ordered project bundle follow project order:

width = torch.tensor(31.0, dtype=torch.float64, requires_grad=True)
sidewall_angle = torch.tensor(88.0, dtype=torch.float64, requires_grad=True)

results = jcmsuite.torch.solve(
    ["project.jcmp", "project.jcmp"],
    keys={
        "h": 55.0,
        "width": width,
        "swa": sidewall_angle,
        "radius": 8.0,
        "permittivity": 1.967 + 4.443j,
    },
    temporary=True,
    key_derivative_map=(
        {"width": RealDerivative("width_parameter")},
        {"swa": RealDerivative("swa")},
    ),
)

Pass one derivative map per project in bundle order. An empty map is an explicit opt-out for an entry. A project key cannot be shared between entries in an 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 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 to_df() and to_xarray() with UnsupportedExportError. Use untorch() to access the ordinary result when you need DataFrame or xarray exports.

Compute Second Derivatives

Set Order = 2 in the project. Existing RealDerivative and 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 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 project keys are scalar Torch tensors. Tensor-valued 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 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 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 untorch() when you need raw solver derivative data or ordinary result navigation.

Next Steps

Tutorials