Skip to main content

SPECTRA-RCWA: the fastest differentiable RCWA we have benchmarked

PyPI Python License: MIT Paper

Eigendecomposition-free, GPU-batched RCWA with adjoint gradients: 144 solves with gradients in 0.23 s on one RTX 5090, up to 65x faster than TorchRDIT at matched accuracy and 218x faster than torcwa.

value and gradient, one RTX 5090 SPECTRA-RCWA TorchRDIT 0.2.0 torcwa 0.1.4.2 batched GPU eigendecomposition S4 (value only)
0.25 µm layer, 64 x 64 design values, 144 solves 0.23 s 10.9 s (R-DIT order 15, one slice)
1 µm layer, 64 x 64 design values, 144 solves 0.30 s 19.4 s (R-DIT order 20, 0.25 µm slices set by hand)
0.8 µm layer, 128 x 128 design values, 144 solves 0.252 s 54.8 s 10.2 s 529 s on 12 CPU cores
gradient error, 0.8 µm layer (grey design) 2.7e-6 5.9e-3 1.8e-3 no gradient

All runs use (8, 8) Fourier orders (578 x 578 layer matrices) and 144 solves (16 incidence directions x 9 wavelengths), each for both polarisations; the GPU codes run in complex64, and S4 gives the value alone, on an Intel i7-12700. The value errors of TorchRDIT in its two rows are 8.4e-6 and 3.7e-5, those of SPECTRA-RCWA 3.6e-6 and 5.2e-6; with one slice at 1 µm, TorchRDIT is wrong by more than 100. Records: benchmarks/results/.

SPECTRA-RCWA is an open-source (MIT) solver for periodic layered structures by rigorous coupled-wave analysis (RCWA, also called the Fourier modal method, FMM) that needs no eigendecomposition. It is written in PyTorch, runs many solves as one batch on a GPU (or on the CPU), and returns diffraction efficiencies, fields and the gradient of any objective with respect to every pixel of the pattern from one adjoint field. Use it to simulate and optimise diffraction gratings, metagratings, metasurfaces, photonic-crystal slabs, thin-film stacks and colour routers, in particular when an inverse design needs value and gradient over many wavelengths and incidence angles, for thick or multilayer patterns, or near the cutoff of a diffraction order, where eigendecomposition gradients fail.

If SPECTRA-RCWA is useful to you, a GitHub star helps other researchers find it.

pip install spectra-rcwa            # or, from source: pip install git+https://github.com/hyoseokp/spectra-rcwa
pip install "spectra-rcwa[mcp]"     # adds the MCP server for AI agents (spectra-rcwa mcp)
import math, torch
from spectra_rcwa import ColorRouterForward, Ray, Stack

# lamellar grating: index-2.0 ridges in air, period 1 um, depth 0.5 um, fill factor 0.5; 633 nm at 10 degrees; 41 orders
stack = Stack(period_um=(1.0, 1.0), thickness_um=0.5, density_shape=(512, 1), fourier_orders=(20, 0), eps_design=4.0)
fwd = ColorRouterForward(stack=stack, rays=[Ray(math.radians(10.0), 0.0, 1.0)], wavelengths_nm=[633.0], dtype=torch.complex128)
x = torch.arange(512) / 512                                     # sample positions in periods
rho = ((x >= 0.25) & (x < 0.75)).double()[:, None].requires_grad_()   # density: 1 = ridge, 0 = air
T, R = fwd.efficiencies([(rho, 0.5)])                           # [solves, orders, (p, s)]; order m at index m + 20
print(T[0, 21], T.sum(1) + R.sum(1))                            # +1 order (0.4408, 0.2656); T + R = 1 for a lossless grating
T[0, 21, 0].backward()                                          # rho.grad: d(+1 order, p) / d(density)

Measured (complex64 on one RTX 5090 unless named; records in benchmarks/results/):

  • 144 solves with 578 x 578 layer matrices (16 incidence directions x 9 wavelengths, both polarisations, (8, 8) orders) give the value and the gradient with respect to all 64 x 64 design values of a 0.25 µm layer in 0.23 s.
  • Against TorchRDIT 0.2.0 on the same problems and GPU, at matched accuracy: 47 times faster for a 0.25 µm layer and 65 times for 1 µm, with one third to one half of the peak GPU memory (6.0 against 18.9 GiB, 8.4 against 14.0 GiB). TorchRDIT's one-slice series is wrong beyond about 0.3 µm of thickness (relative errors above 100 at 1 µm) and needs slices chosen by hand; SPECTRA-RCWA needs no setting for the thickness.
  • On a 144-solve evaluation with 128 x 128 design values (a 0.8 µm layer, 16 directions x 9 wavelengths), value and gradient take 0.252 s, 218 times less than torcwa (54.8 s) on the same GPU. The gradient agrees with a complex128 reference to 2.7e-6, and to 3.8e-5 on a layer with an order at cutoff, where torcwa's gradient is wrong by 0.49.

Agents: read AGENTS.md, or run spectra-rcwa mcp for tools that set up, check and solve a grating problem (llms.txt).

How it works · Install · Efficiencies · Scope and conventions · Speed and accuracy · Agents and MCP · Citation

SPECTRA-RCWA stands for a spectral propagation engine for coupled-wave theory with recursive admittance.

Figure 1

Figure 1: One objective over many wavelengths, angles and polarisations as one batch of matrix products, with no eigendecomposition. (a) A periodic stack of patterned layers, each cut into steps of thickness h. All wavelengths, incidence angles and both polarisations of an objective are solved as one batch; the admittance Y is swept up the stack and the adjoint field down it, which gives the gradient with respect to every pattern value. (b) Modal RCWA diagonalises the layer matrix A = PQ, one solve at a time, as VΛV⁻¹; its propagation constants are square roots of the eigenvalues λ, which are singular at the cutoff of an order (λ = 0), and so is the gradient. (c) SPECTRA-RCWA forms C = cos(ωhA^(1/2)), S = sin(ωhA^(1/2))/A^(1/2) and G = (C − I)/A for all B solves at once by matrix products (scaling, a polynomial and double-angle steps). These are entire functions of A, smooth at the cutoff. On one RTX 5090, 144 solves with 578 x 578 layer matrices give value and gradient in 0.23 s, 47 to 65 times faster than TorchRDIT at matched accuracy and 218 times faster than torcwa.

What it does

Classical RCWA diagonalises the layer matrix A = PQ and builds the layer S-matrix from the eigenvectors W and the eigenvalues kz². The S-matrix never needs the eigenvectors themselves: every expression W f(kz) W⁻¹ is a matrix function of A. Since the fields obey e′ = iωPh and h′ = iωQe (z downward), a step h of a layer needs only functions that are entire in A, with no square root:

C = cos(ωh A^(1/2)),   S = sin(ωh A^(1/2)) / A^(1/2),   G = (C − I) / A
e(0) = C e(h) − iS P h(h),   h(0) = −iQS e(h) + (I + QGP) h(h)

From the output medium upwards, with h(h) = Y e(h):

D = (C − iSPY)⁻¹,   e(h) = D e(0),   Y_top = (Y + QGPY − iQS) D

This package computes

  • C, S and G by scaling, a degree-6 polynomial in A (Paterson–Stockmeyer, four GEMMs) and double-angle steps on C − I, which unlike steps on C lose no digits while the argument is small: GEMMs only (spectra_rcwa.matfun.cos_sinc);

  • the recursion with one batched pivoted inverse per step and an output-to-input pass over two right-hand sides. An evanescent order makes C and S large, so a layer is cut in steps with ωh max(k) at most 4.5 (SolverConfig.max_step_phase): 3 steps for 0.25 µm at (8, 8) orders;

  • for a layer of 7 steps or more (SolverConfig.block_from_steps; 0.8 µm at (8, 8) orders) its S-matrix instead: one thin step in the wave basis of a fixed reference admittance, then Redheffer products of the layer with itself, r doublings for 2^r steps with r + 1 inverses (spectra_rcwa.blocks);

  • the gradient from one adjoint field (spectra_rcwa.adjoint), with no graph. The objective needs the field for two incident polarisations only, and for a variation of P and Q

    dJ = Re ∫ iω (a^H dP h + b^H dQ e) dz,   a' = iω Q^H b,   b' = iω P^H a
    

    with a = V_i^H b at the top of the stack and a + V_o^H b = dJ/d(field below) at its bottom. The factors saved by the forward pass give (e, h) and (a, b) on the planes between the steps, stable in both directions, in products with two columns; a short Taylor series from each plane gives them on Gauss–Legendre nodes, and the integral is a low-rank sum;

  • P and Q by structure: P = J + K_L E⁻¹ K_R and Q = −K_L K_R + [[0, −E], [E, 0]] with K_R K_L = 0, so A = PQ needs two GEMMs of a quarter of the size, a product with P costs a quarter of a dense GEMM and one with Q half of it. The elementwise parts run as single NVRTC passes (spectra_rcwa.kernels).

There is no eigensolver, no square root, no branch choice and no P⁻¹. All solves of an evaluation go into one batch on the GPU, the gradient has neither 1/(λi − λj) nor 1/√λ terms, and a layer order at cutoff (λ near 0) needs no special handling. In complex128 the adjoint field agrees with autograd through the same forward pass to about 1e-14. AUTOGRAD_ROUTE switches off the adjoint field, for comparison: autograd through dense P and Q (the products by structure run without a graph only), pivoted inverses, degree 8, the route of the commit before them.

Thick layers and stored layers

A layer's S-matrix depends on that layer alone, so it can be kept, for instance for a layer stack below a design that does not change:

with torch.no_grad():                                  # a stored layer needs no graph
    pd = fwd.layer_block(rho_pd, 3.0)                  # (T, R), each [solves, 2N, 2N], in a fixed reference basis
below = fwd.stack_field([(rho_a, 0.25), (rho_b, 0.25), pd])                  # field below the stack, [solves, 2N, 2]
below, top = fwd.stack_field([(rho_a, 0.25), pd], return_top=True)           # and at the top of it

The reference medium is a fictitious lossy one (ε = 4 + 4i), so I − RR has no real pole at a guided mode of the layer and no order has a Rayleigh point in it, unlike a vacuum basis. Both routes against complex128 through Γ with 14 iterations, which they match to 6.5e-13 in complex128 (complex64; RTX 5090; (8, 8) orders, 540 nm; errors for one ray, time and memory for 16 rays in one batch):

layer route value error gradient error T and R error time per solve (ms) memory per solve (MiB)
SiN 0.8 µm recursion, 7 steps 1.4e-08 3.2e-05 1.1e-06 5.5 59
SiN 0.8 µm doubling, 8 steps 7.5e-08 9.1e-06 5.6e-06 3.2 48
SiN 1.5 µm recursion, 12 steps 2.0e-08 3.3e-05 2.4e-06 9.3 96
SiN 1.5 µm doubling, 16 steps 1.3e-09 1.2e-05 5.6e-07 3.6 61
SiN 3 µm recursion, 24 steps 1.0e-07 5.8e-05 4.9e-06 16.6 172
SiN 3 µm doubling, 32 steps 2.9e-08 2.9e-05 1.9e-06 4.0 80
Si (ε = 17.1 + 0.28i) with a 0.2 µm oxide trench, 3 µm recursion, 24 steps 1.7e-07 5.8e-05 1.6e-05 16.8 172
Si (ε = 17.1 + 0.28i) with a 0.2 µm oxide trench, 3 µm doubling, 32 steps 8.8e-09 7.7e-05 5.1e-06 4.1 80

The absorbing layer has A = 0.7149 and 0.7143 (reference 0.7149 and 0.7143) for the two polarisations, with A = 1 − T − R from the fluxes; in the lossless layers that A is at most 5.6e-06. Central differences of complex128 along the adjoint gradient at 3 µm: 0.0094546 against its norm 0.0094544 (SiN, recursion), 0.0094546 against 0.0094545 (SiN, doubling), 0.0051844 against 0.0051847 (Si, doubling). Per solve, doubling is faster from about 3 steps on (6.5 against 5.6 ms at 3 steps and 10.0 against 6.5 ms at 7, in a stack of two), but it keeps more matrices for the gradient: 8 layers of 0.25 µm through doubling do not fit in 32 GB at 144 solves, so a layer goes through its S-matrix from 7 steps on. The two Si rows were measured with 6 quadrature nodes per step in the gradient; from version 1.0.0 the node count follows ωh|ε|^(1/2), and those two cases use 10.

Option: the route through Γ, before the patch

SolverConfig(boundary="direct", boundary_inverse="block") is the earlier route, before the entire functions, kept as an option and as a check, and boundary="smatrix" with REFERENCE_C128 its converged complex128 reference. Γ = A^(1/2) (branch Im kz ≥ 0) comes from the product form of the Denman–Beavers iteration with norm scaling μ = (‖M⁻¹‖ / ‖M‖)^(1/4), the exact identity Y₀M₀⁻¹ = I in the first step, and a third-order series for M^(−1/2) at the end (4 batched inverses plus GEMMs); E = exp(iωdΓ) from scaling and squaring with a degree-18 Taylor polynomial; the boundary conditions from a 2 x 2 block system eliminated with two inverses and an adjoint written by hand with O(n²r) work beyond the saved inverses (r = 2 polarisations). The CUDA path adds hand-written backward passes for the Denman–Beavers steps and the squarings, NVRTC-compiled fused kernels for linear combinations and for K_i = P Y_i, K_o = P Y_o, a sync-free pivoted batched LU, and a block-recursive (GEMM-only) inverse for the well-conditioned matrices (spectra_rcwa.kernels). Everything falls back to plain PyTorch on the CPU.

This route is not reliable at an order at cutoff, because Γ is not analytic at λ = 0. Value and gradient are smooth there only through cancellations: if P has the small singular value (about |λ|), the adjoints of P through A = PQ and through K = PY each grow as 1/|λ| and sum to O(1). That needs Γ² = PQ far below the rounding error of a complex64 A, so computing Γ and E alone in complex128 does not help, and an iteration converged for λ, which 4 Denman–Beavers steps are not at any precision; with a small complex pair of eigenvalues 4 steps give a wrong value with no sign of it (T = 0.76 where the converged value is 0.96). The relative gradient error grows as 1/λ². On an 8-layer design about one layer solve in 288 has ‖A⁻¹‖_F above 1e6, and such a solve can dominate the gradient of the whole evaluation. That is why the default changed. Default route (this work) against the route through Γ on an RTX 5090:

design route value + gradient (s) peak memory (GiB) value error gradient error (rel. L2)
grey, 144 solves, the objective default 0.253 6.6 3.2e-06 (Tabs) 2.7e-06
same through Γ 0.436 15.9 6.8e-06 (Tabs) 7.2e-04
binary, 144 solves, the objective default 0.264 6.6 3.4e-06 (Tabs) 8.2e-06
same through Γ 0.434 15.9 6.3e-06 (Tabs) 4.3e-03
one layer of an 8-layer SiN/SiO2 design, 0.25 µm, 144 solves, the objective, with a solve at ‖A⁻¹‖_F = 4.5e6 default 0.201 5.3 1.2e-06 (Tabs) 3.8e-05
same through Γ 0.408 14.8 7.7e-06 (Tabs) 5.1e-01
that 8-layer design, MultiLayerForward, random weights on Tabs, 16 rays at 420 nm default 0.31 3.0 8.2e-06 3.2e-05
same through Γ, no TF32 1.7 15.2 1.6e-05 1.2e-02

On the third case, central differences of complex128 along the gradient give 0.000665 against its norm 0.000665 for the reference, 0.000665 against 0.000665 for the default route, and 0.000603 against 0.000793 for the route through Γ.

Older measurements, kept in benchmarks/results/summary.json: the route through Γ on an H200 (0.386 s complex64, 0.822 s complex128) and an RTX 5880 Ada (0.858 s); not measured again on those.

Install

pip install spectra-rcwa              # or pip install git+https://github.com/hyoseokp/spectra-rcwa
pip install "spectra-rcwa[mcp]"       # the MCP server for agents

From a checkout:

pip install -e .            # torch >= 2.6 and numpy; complex64 on CUDA needs torch >= 2.8
pip install -e ".[test]"    # pytest
pip install -e ".[figures]" # matplotlib, for scripts/make_figures.py

The NVRTC kernels of the complex64 CUDA path use torch.cuda._compile_kernel (torch 2.8 or newer; tested with 2.10.0), and the CPU and complex128 run on plain torch; the torch wheel is enough, no CUDA toolkit or CUDA_HOME is needed. If the cuBLAS library that torch loaded is not found automatically, set SPECTRA_RCWA_CUBLAS to its path.

Minimal example

import torch
from spectra_rcwa import ColorRouterForward, Stack, shifted_disk_pupil, value_and_grad

stack = Stack(period_um=(2.0, 2.0), thickness_um=0.8, density_shape=(64, 64), fourier_orders=(4, 4),
              eps_design=2.05 ** 2, eps_fill=1.0, eps_in=1.0, eps_out=1.46 ** 2, detector_z_um=1.25)
rays = shifted_disk_pupil(numerical_aperture=0.30, chief_ray_angle_deg=2.5, chief_ray_azimuth_deg=22.5)
fwd = ColorRouterForward(stack=stack, rays=rays, wavelengths_nm=(450.0, 540.0, 630.0))     # on the GPU if there is one

density = torch.rand(64, 64)
tabs = fwd.response(density.to(fwd.device))   # Tabs[well (R, G2, G1, B), wavelength], float64, differentiable
target = torch.eye(4, 3, dtype=torch.float64)
tabs, value, grad = value_and_grad(fwd, density, lambda t: (t * target).sum())

examples/minimal.py runs a smaller case of it on CPU or GPU. Permittivities can be numbers or functions of the wavelength in µm. SolverConfig holds the solver options; DEFAULT is the configuration used for every number below, and REFERENCE_C128 is a converged complex128 configuration used as the accuracy reference.

Diffraction efficiencies

ColorRouterForward.efficiencies(layers) returns (T, R), the power in every diffraction order of the substrate and of the superstrate over the incident power, [solves, N, 2] with one column per incident polarisation, for any stack that stack_field takes; stack_field itself returns the tangential electric field below and on top of the stack. Tabs, the table of the four detector quadrants, is the output that the colour-router objective uses.

t, r = fwd.efficiencies([(rho_a, 0.25), (rho_b, 0.25)])      # order (m, n) at index (m + M) * (2 N + 1) + (n + N)

Scope and conventions

  • Rectangular lattices with periods along x and y. The two periods, the two order counts and the two sides of the design grid can differ, and fourier_orders=(M, 0) is a 1D grating. All (2M + 1)(2N + 1) orders are kept, and the permittivity enters by the Laurent rule with E⁻¹ in P, as in torcwa, so metals and other high-contrast patterns converge slowly in the orders.
  • A pattern mixes two isotropic, non-magnetic materials linearly through the density, and MultiLayerForward uses the same two in every layer; a uniform layer is density 0 or 1. A layer of other materials goes into stack_field as the layer_block of a second forward with the same lattice, orders, rays and wavelengths.
  • The time dependence is exp(−iωt), so absorption is Im ε > 0. Lengths are in µm, wavelengths in nm and Ray angles in radians (polar angle from z in the reference medium, azimuth from x). Light comes from the superstrate, which is lossless. The two columns of a field are the polarisations p cos φ − s sin φ and p sin φ + s cos φ, which are x and y at normal incidence.
  • density[i, j] is the sample at x = iΛx/H, y = jΛy/W (band-limited samples, first index along x), with H and W at least 4 × orders + 1. The detector samples sit at (k + 0.5)Λ/S, and a well is its share of |E|² on the detector plane, a midpoint rule on detector_samples, times the total transmission.
  • Every solve runs at the frequency (1 + rayleigh_nudge)/λ, 1e-4 by default, so that no order of the half-spaces sits on a Rayleigh point; π is torcwa's 3.141592652589793, to match it digit for digit.
  • On CUDA the solver selects MAGMA for the process (SolverConfig.linalg_library; an empty string leaves the setting alone) and expects TF32 products off, which is torch's default. One GPU per process: the kernels belong to the current CUDA device.
  • The factors of a solve live as long as its graph. In a loop, drop the outputs of the last evaluation (del tabs, loss, or evaluate inside a function, as value_and_grad does) before the next forward; otherwise two sets of factors are held at once.

Multi-layer stack

MultiLayerForward(thicknesses_um=(...), ...) stacks several patterned layers (density [layers, H, W]), with the admittance recursion above running through all of them. The tests check that one layer equals the direct boundary solve and that two layers of thickness d/2 equal one layer of thickness d. With the routes through Γ the layers are combined by Redheffer products in a vacuum gap basis, which puts real poles at guided modes of the layers. chunk bounds the solves per batch, and responses takes several stacks [S, layers, H, W].

On an RTX 5090, value + gradient for 2 µm of total thickness, 144 solves in one batch unless named, the objective:

layers layer thickness (µm) solves per chunk value + gradient (s) peak memory (GiB)
1 2 144 0.371 10.8
2 1 144 0.651 15.3
4 0.5 144 1.05 20.2
8 0.25 144 1.47 26.8

A real 8-layer design of 128 x 128 per layer takes 1.47 s and 26.8 GiB for 144 solves. Its exact mirrors (i to 128 − i on the design grid, and x and y exchanged), with the rays and wells mirrored, give the same Tabs to 6.5e-06.

Speed and accuracy

One evaluation = a colour-router objective on Tabs (not part of this package) and its gradient with respect to all 128 x 128 density values, 16 rays (NA 0.30, CRA 2.5°) x 9 wavelengths = 144 solves, each for both polarisations, (8, 8) Fourier orders (578 x 578 layer matrices), 800 nm SiN layer, grey design unless named, complex64. Errors are against complex128 through Γ with 14 iterations, solved one ray at a time.

S4 (CPU) torcwa (GPU) crfast (GPU) this work (GPU)
hardware i7-12700, 12 processes RTX 5090 RTX 5090 RTX 5090
value (s) 529 25.5 8.85 0.217
value, speed-up against S4 on 12 processes 1x 21x 60x 2,440x
value + gradient (s) no gradient 54.8 10.2 0.252
value + gradient, against this work 218x 41x 1x
per solve, value + gradient (ms) 381 71 1.75
peak GPU memory (GiB) 4.8 4.2 6.6
Tabs error (max rel.), grey 3.4e-02 from torcwa 8.9e-06 6.0e-06 3.2e-06
gradient error (rel. L2), grey 5.9e-03 1.8e-03 2.7e-06
gradient error, binary 7.2e-02 5.4e-02 8.2e-06
gradient error, a layer with an order at cutoff 4.9e-01 2.0e+00 3.8e-05

All measured. S4 was run once, on the CPU named, and gives the value only: 5238 s in a single process (24,100x against this work, 2,440x on 12 processes, on different hardware); it agrees with torcwa on the transmission to 1.7e-04. torcwa runs its solves one by one, each polarisation separately, with torch's default linear algebra library, 4 CPU threads for the eigendecomposition (the thread count hardly matters: 25.5 to 25.7 s at 16), and a checkpoint per wavelength for the gradient: the graph of 288 solves would hold 41 GiB. Sharing the eigendecomposition between the polarisations brings its value to 13.4 s, but that path is not differentiable. With MAGMA selected for the whole process, as the default route of this package does, its value pass takes 80.6 s. crfast: batched eigendecomposition on the GPU, 48 solves at a time, warm start off; 13.6 s with it in 16 CPU workers. In complex128, in chunks of 24 solves, this work takes 16.9 s and gives the objective to 7.1e-15.

TF32 costs far more accuracy than time at every stage of this route (worst gradient error of six cases, against 7.7e-05 without): cos sin 1.1e-02 at 237 ms, thin step 8.0e-02 at 246 ms, doubling 1.8e-02 at 208 ms, below block 3.4e-04 at 247 ms, inverses 1.1e-02 at 243 ms, adjoint planes 1.5e-03 at 253 ms, adjoint integral 3.3e-04 at 253 ms, adjoint whole 2.7e-03 at 251 ms, against 253 ms, so it is off. The six cases are grey, binary, the layer at cutoff, the 8-layer design, 3 µm of SiN and 3 µm of Si with a trench.

Single solve

Value + gradient per polarisation, complex64 on the RTX 5090. One solve of torcwa takes 95 ms and of this work, for both polarisations, 34 ms; in the batch a solve costs 1.75 ms.

single solve

Where the time goes

stage breakdown

One evaluation of the 800 nm layer on the RTX 5090 (forward 220 ms, gradient 32 ms).

Hardware

  • RTX 5090 (32 GB), AMD Ryzen 9 7950X 16-Core Processor, torch 2.10.0+cu128, driver 595.91.07: every number of this work, torcwa 0.1.4.2 and crfast above, unless named otherwise.
  • RTX 4090 (24 GB), same torch: the same evaluation takes 0.391 s (0.297 s for the value) and 6.6 GiB, gradient error 2.7e-06; 8 layers, 144 solves, in chunks of 36 (a value pass, then a forward and gradient pass per chunk) take 4.76 s and 13.1 GiB (benchmarks/results/rtx4090.json).
  • S4 (Python extension built from source with OpenBLAS), Ubuntu 22.04 under WSL2 on an i7-12700 (12 cores).

Tests

pytest

CPU tests (complex128 and complex64): the entire functions, matrix square root and exponential against eigendecomposition and torch.linalg.matrix_exp; hand-written backward of the Denman–Beavers step and of the squarings against autograd; block-recursive inverse; direct boundary solve against the reference formula, the S-matrix route and eigendecomposition RCWA (air and glass superstrate); its adjoint against autograd and gradcheck; one layer equals two half layers; full response against eigendecomposition RCWA; central finite-difference gradient checks in complex128 (single and multi-layer); solves tuned to an eigenvalue 1e-6 with P or with Q nearly singular (one layer, a stack, a batch with one such solve), against complex128 on both sides of the cutoff. CUDA tests (fused kernels against torch, pivoted and block inverses, hand-written backward on the GPU, complex64 GPU response and a solve at cutoff against the complex128 CPU reference) are skipped without a GPU. tests/test_adjoint.py: the adjoint field against autograd in complex128 (recursion, doubling, stacks, both outputs of a solve, stored blocks) and complex64, on the CPU and the GPU, the kernels, and the exact mirrors of the lattice in a batch of 48 solves. tests/test_general.py: diffraction efficiencies against energy conservation and the Airy formula of a slab, a rectangular cell with unequal orders and a 1D grating, the adjoint for a layer index above the largest transverse wave vector, the checks on the arguments, chunks, the energy guard, and large matrices after torch.set_num_threads.

torch.linalg.solve_triangular gives wrong results for a complex64 batch of 16 or more with the factors of a matrix that needs pivoting (residual about 7 instead of 1e-3; 578 x 578, torch 2.10.0+cu128, RTX 5090, with the library set to MAGMA or left at its default; a batch of 8 or less is right, and so are diagonally dominant matrices). The routes here do not call it: spectra_rcwa.kernels.pivlu.lu_solve has its own triangular solves. tests/test_cuda.py measures the residual of every batched solver the routes use at a batch of 144 and 288, and keeps this case as an expected failure.

Reproducing the benchmarks

benchmarks/results/ holds the measurements behind the tables and figures here: rtx5090.json and rtx5090_stages.json for this work (rtx4090*.json on the RTX 4090), rtx5090_torcwa.json, rtx5090_crfast.json, summary.json for S4 and the older measurements, route_through_gamma_failures.json for the failure described above, solve_triangular_residuals.json for the note on solve_triangular, and torchrdit_rtx5090_025um.json and torchrdit_rtx5090_1um.json for the comparison with TorchRDIT 0.2.0 at the top of this page. They were measured with a colour-router objective, design files and comparison code that are not distributed here. python scripts/make_figures.py regenerates docs/figures/ from these files.

benchmarks/bench_synthetic.py runs a problem of the same size (144 solves, (8, 8) orders, 128 x 128 design values, 0.8 µm layer) on a synthetic freeform pattern with a fixed linear objective, using nothing outside this package, and reports time, peak memory and the error against complex128 for one ray:

cd benchmarks
python bench_synthetic.py results/synthetic.json            # on the GPU if there is one
python bench_synthetic.py synthetic_small.json --small      # a small case for a CPU

AI agents and MCP

AGENTS.md tells an agent when the package fits, how to set up a problem, how to check it and which pitfalls to avoid; llms.txt and llms-full.txt are the same material for language models. The command line takes problems as JSON:

spectra-rcwa example lamellar_grating > grating.json     # also pillar_array, slab, two_layer_grating
spectra-rcwa check grating.json                          # errors, warnings, size
spectra-rcwa solve grating.json                          # efficiencies of every propagating order, p and s

spectra-rcwa mcp serves seven tools over stdio (pip install "spectra-rcwa[mcp]"): environment, example_problem, problem_schema, validate_problem, solve_efficiencies, efficiency_gradient and convergence_in_orders. Register it in any MCP client as the command spectra-rcwa with the argument mcp, for example claude mcp add spectra-rcwa -- spectra-rcwa mcp. In Claude Code the repository is also a plugin marketplace with a skill and the server:

/plugin marketplace add hyoseokp/spectra-rcwa
/plugin install spectra-rcwa@spectra-rcwa

Citation

A manuscript describing SPECTRA-RCWA is in preparation; until it appears, cite the software (CITATION.cff gives GitHub's "Cite this repository"):

@software{spectra_rcwa,
  author  = {Park, Hyoseok},
  title   = {{SPECTRA-RCWA}: eigendecomposition-free batched {RCWA} forward and adjoint in {PyTorch}},
  url     = {https://github.com/hyoseokp/spectra-rcwa},
  version = {1.1.1},
  year    = {2026}
}

License

MIT, see LICENSE.

Metadata

Release files for spectra-rcwa 1.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for spectra-rcwa 1.2.0
File Size Uploaded Provenance Actions
spectra_rcwa-1.2.0.tar.gz 93.0 kB With provenance Details for spectra_rcwa-1.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for spectra-rcwa 1.2.0
File Interpreter ABI Platform Actions
spectra_rcwa-1.2.0-py3-none-any.whl Python 3 none any Details for spectra_rcwa-1.2.0-py3-none-any.whl

Total release size: 171.2 kB

Release files / spectra_rcwa-1.2.0.tar.gz

Download URL spectra_rcwa-1.2.0.tar.gz
Size 93.0 kB
Tags Source
SHA-256 checksum
How to use checksums
c6639e32949f88a42d7049a085bcbf6682bad5c6d1f1e2f8260d1b8192ccb6cf
BLAKE2b-256 checksum
How to use checksums
c94c8e230284aba280c6b35022ff0a0786b70a401f20e4abe54245ad973d516e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.

Transparency log

Release files / spectra_rcwa-1.2.0-py3-none-any.whl

Download URL spectra_rcwa-1.2.0-py3-none-any.whl
Size 78.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
de0cf16567cd7c79c5b61ddd6dd421bc086cd13af62e548b37aeba5437d105ea
BLAKE2b-256 checksum
How to use checksums
8e55a32918165d0a515286a1d39b7b10f700bdf796394b0fe5b9f26572cbe8d0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.

Transparency log

Security for spectra-rcwa 1.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for spectra_rcwa-1.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.2.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page