Skip to main content

refloxide_gpu/
lib.rs

1//! Portable GPU backend for the decoupled uniaxial recursion.
2//!
3//! Dispatches [`refloxide_tmm::kernel::solve_point_recursive`] as a WGSL compute
4//! shader through `wgpu`, which targets Metal (Apple), Vulkan (NVIDIA, AMD,
5//! Intel, Linux/Windows) and DX12 (Windows) from one source. Arithmetic is
6//! single precision; the recursion's cancellation-free formulation keeps
7//! relative reflectance error near `1e-5` against the double-precision 4x4
8//! reference (see the `kernel_precision` example of `refloxide-tmm`).
9//!
10//! [`GpuContext::reflectivity_points_general`] additionally runs the general
11//! dielectric-tensor 4x4 engine ([`refloxide_tmm::kernel::solve_point_general`]).
12//! It needs double precision to be accurate for tilted and biaxial layers,
13//! which requires native `f64` shaders (wgpu `SHADER_F64`: Vulkan and DX12
14//! adapters, not Metal); see [`GpuContext::supports_f64`].
15//!
16//! This module does not provide amplitude transmission, and it does not
17//! validate physics inputs beyond buffer shapes. A [`GpuContext`] owns one
18//! device and compiled pipelines and should be created once and reused:
19//! device acquisition and shader compilation cost far more than a dispatch.
20
21use std::sync::{mpsc, OnceLock};
22
23use bytemuck::{Pod, Zeroable};
24use nalgebra::Matrix3;
25use num_complex::Complex;
26use wgpu::util::DeviceExt;
27
28use refloxide_core::{
29    jvp_coeffs, layer_coeffs, validate_batch, validate_points, wavenumber, Layer, LayerCoeffs,
30    PointsJvpOutput, PointsTangents, RefloxideError, Result, UniaxialBatchOutput, UniaxialOutput,
31};
32use refloxide_tmm::kernel::GeneralLayer;
33
34const WORKGROUP_SIZE: u32 = 64;
35
36/// Double-single arithmetic library prepended to df64 shaders.
37const DF64_WGSL: &str = include_str!("df64.wgsl");
38
39/// General-tensor 4x4 shader body and its per-precision preludes.
40const GENERAL_WGSL: &str = include_str!("general.wgsl");
41const GENERAL_F32_WGSL: &str = include_str!("general_f32.wgsl");
42const GENERAL_F64_WGSL: &str = include_str!("general_f64.wgsl");
43
44/// Operation probed by [`GpuContext::df64_selftest`].
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum Df64Op {
47    /// `a + b`.
48    Add,
49    /// `a * b`.
50    Mul,
51    /// `a / b`.
52    Div,
53    /// `sqrt(a)`.
54    Sqrt,
55    /// `exp(a)`.
56    Exp,
57    /// `sin(a)`.
58    Sin,
59    /// `cos(a)`.
60    Cos,
61    /// `ln(a)`.
62    Log,
63    /// Error term of the f32 two-sum of `a` and `b` (reassociation canary:
64    /// identically zero if the compiler folds `(a - (s - v)) + (b - v)`).
65    TwoSumError,
66}
67
68/// Numeric precision of the general-tensor shader build.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum GeneralPrecision {
71    /// Native `f64` shader arithmetic; requires [`GpuContext::supports_f64`].
72    F64,
73    /// Single precision with hardware transcendentals. Runs on every
74    /// adapter, but loses 4-48% of reflectance on tilted and biaxial stacks
75    /// (see the `kernel_precision` example of `refloxide-tmm`); intended for cross-checking the
76    /// shader logic against the CPU kernel, not for fitting.
77    F32,
78}
79
80/// Reals per general-shader layer record: 18 for `chi`, thickness, sigma.
81const GENERAL_STRIDE: usize = 20;
82
83/// Splits an `f64` into the `(hi, lo)` f32 pair of its df64 representation.
84fn to_df64(x: f64) -> [f32; 2] {
85    let hi = x as f32;
86    [hi, (x - f64::from(hi)) as f32]
87}
88
89#[repr(C)]
90#[derive(Clone, Copy, Pod, Zeroable)]
91struct GpuLayer {
92    chi_o: [f32; 2],
93    chi_e: [f32; 2],
94    thickness: f32,
95    sigma: f32,
96}
97
98#[repr(C)]
99#[derive(Clone, Copy, Pod, Zeroable)]
100struct Params {
101    n_points: u32,
102    n_layers: u32,
103    n_stacks: u32,
104    row_pitch: u32,
105}
106
107/// df64 layer record: complex values as `[re.hi, re.lo, im.hi, im.lo]`.
108#[repr(C)]
109#[derive(Clone, Copy, Pod, Zeroable)]
110struct GpuLayerDf64 {
111    chi_o: [f32; 4],
112    chi_e: [f32; 4],
113    thickness: [f32; 2],
114    sigma: [f32; 2],
115}
116
117#[repr(C)]
118#[derive(Clone, Copy, Pod, Zeroable)]
119struct JvpParams {
120    n_points: u32,
121    n_layers: u32,
122    n_stacks: u32,
123    row_pitch: u32,
124    n_dirs: u32,
125    _pad: [u32; 3],
126}
127
128/// Device, queue, and compiled recursion pipelines for one GPU adapter.
129pub struct GpuContext {
130    device: wgpu::Device,
131    queue: wgpu::Queue,
132    pipeline: wgpu::ComputePipeline,
133    jvp_pipeline: wgpu::ComputePipeline,
134    df64_selftest_pipeline: wgpu::ComputePipeline,
135    df64_pipeline: wgpu::ComputePipeline,
136    general_f32_pipeline: OnceLock<wgpu::ComputePipeline>,
137    general_f64_pipeline: OnceLock<wgpu::ComputePipeline>,
138    has_f64: bool,
139    info: wgpu::AdapterInfo,
140    limits: wgpu::Limits,
141}
142
143fn compile_pipeline(device: &wgpu::Device, label: &str, source: &str) -> wgpu::ComputePipeline {
144    let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
145        label: Some(label),
146        source: wgpu::ShaderSource::Wgsl(source.into()),
147    });
148    device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
149        label: Some(label),
150        layout: None,
151        module: &module,
152        entry_point: Some("main"),
153        compilation_options: Default::default(),
154        cache: None,
155    })
156}
157
158fn gpu_layers(layers: &[LayerCoeffs<f32>]) -> Vec<GpuLayer> {
159    layers
160        .iter()
161        .map(|l| GpuLayer {
162            chi_o: [l.chi_o.re, l.chi_o.im],
163            chi_e: [l.chi_e.re, l.chi_e.im],
164            thickness: l.thickness,
165            sigma: l.sigma,
166        })
167        .collect()
168}
169
170fn to_u32(v: usize, what: &str) -> Result<u32> {
171    u32::try_from(v).map_err(|_| RefloxideError::InvalidShape(format!("{what} exceeds u32")))
172}
173
174fn check_points(
175    n_points: usize,
176    stack_of: &[u32],
177    n_stacks: usize,
178    n_records: usize,
179    n_layers: usize,
180) -> Result<()> {
181    if n_layers < 2 {
182        return Err(RefloxideError::InsufficientLayers(n_layers));
183    }
184    if n_records != n_stacks * n_layers {
185        return Err(RefloxideError::InvalidShape(format!(
186            "layers buffer length {n_records} != n_stacks ({n_stacks}) * n_layers ({n_layers})"
187        )));
188    }
189    if stack_of.len() != n_points {
190        return Err(RefloxideError::InvalidShape(format!(
191            "stack_of length {} != q length {n_points}",
192            stack_of.len()
193        )));
194    }
195    if let Some(&bad) = stack_of.iter().find(|&&s| s as usize >= n_stacks) {
196        return Err(RefloxideError::InvalidShape(format!(
197            "stack index {bad} out of range for {n_stacks} stacks"
198        )));
199    }
200    Ok(())
201}
202
203impl GpuContext {
204    /// Acquires the highest-performance adapter available and compiles the shaders.
205    ///
206    /// Backend selection honors the `WGPU_BACKEND` environment variable
207    /// (for example `vulkan`, `metal`, `dx12`) through `wgpu`'s defaults.
208    ///
209    /// # Errors
210    /// [`RefloxideError::Gpu`] when no adapter or device can be obtained.
211    pub fn new() -> Result<Self> {
212        let instance =
213            wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env());
214        let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
215            power_preference: wgpu::PowerPreference::HighPerformance,
216            ..Default::default()
217        }))
218        .map_err(|e| RefloxideError::Gpu(format!("no compatible adapter: {e}")))?;
219        let limits = adapter.limits();
220        let has_f64 = adapter.features().contains(wgpu::Features::SHADER_F64);
221        let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
222            label: Some("refloxide"),
223            required_features: if has_f64 {
224                wgpu::Features::SHADER_F64
225            } else {
226                wgpu::Features::empty()
227            },
228            required_limits: limits.clone(),
229            ..Default::default()
230        }))
231        .map_err(|e| RefloxideError::Gpu(format!("device request failed: {e}")))?;
232        let compile = |label: &str, source: &str| compile_pipeline(&device, label, source);
233        let pipeline = compile("refloxide-recursive", include_str!("recursive.wgsl"));
234        let jvp_pipeline = compile(
235            "refloxide-recursive-jvp",
236            include_str!("recursive_jvp.wgsl"),
237        );
238        let df64_selftest_pipeline = compile(
239            "refloxide-df64-selftest",
240            &[DF64_WGSL, include_str!("df64_selftest.wgsl")].concat(),
241        );
242        let df64_pipeline = compile(
243            "refloxide-recursive-df64",
244            &[DF64_WGSL, include_str!("recursive_df64.wgsl")].concat(),
245        );
246        Ok(Self {
247            device,
248            queue,
249            pipeline,
250            jvp_pipeline,
251            df64_selftest_pipeline,
252            df64_pipeline,
253            general_f32_pipeline: OnceLock::new(),
254            general_f64_pipeline: OnceLock::new(),
255            has_f64,
256            info: adapter.get_info(),
257            limits,
258        })
259    }
260
261    /// Human-readable adapter name and backend, for logs and benchmarks.
262    pub fn describe(&self) -> String {
263        format!("{} ({:?})", self.info.name, self.info.backend)
264    }
265
266    /// Whether the adapter provides native `f64` shader arithmetic.
267    ///
268    /// `true` on Vulkan and DX12 adapters that report `shaderFloat64`;
269    /// `false` on Metal. Gates [`GeneralPrecision::F64`].
270    pub fn supports_f64(&self) -> bool {
271        self.has_f64
272    }
273
274    /// Single-precision reflectance for many equal-depth stacks on a shared q-grid.
275    ///
276    /// # Parameters
277    /// - `q`: scattering vectors in `1/Angstrom`, length `n_q`.
278    /// - `k0`: vacuum wavenumber per stack in `1/Angstrom`, length `n_stacks`.
279    /// - `layers`: row-major `(n_stacks, n_layers)` layer records.
280    /// - `n_layers`: depth of every stack, at least two.
281    ///
282    /// # Returns
283    /// Row-major `(n_stacks, n_q)` pairs `[R_pp, R_ss]`, matching the
284    /// `(0, 0)` and `(1, 1)` entries of [`refloxide_tmm::kernel::PointResult`].
285    ///
286    /// # Errors
287    /// As for [`GpuContext::reflectivity_points`].
288    pub fn reflectivity_flat(
289        &self,
290        q: &[f32],
291        k0: &[f32],
292        layers: &[LayerCoeffs<f32>],
293        n_layers: usize,
294    ) -> Result<Vec<[f32; 2]>> {
295        let n_stacks = to_u32(k0.len(), "n_stacks")?;
296        let q_points: Vec<f32> = (0..k0.len()).flat_map(|_| q.iter().copied()).collect();
297        let stack_of: Vec<u32> = (0..n_stacks)
298            .flat_map(|si| std::iter::repeat_n(si, q.len()))
299            .collect();
300        self.reflectivity_points(&q_points, &stack_of, k0, layers, n_layers)
301    }
302
303    /// Single-precision reflectance for independent `(q, stack)` points.
304    ///
305    /// Each point carries its own stack index, so stacks (for example one
306    /// per photon energy) may be paired with ragged q-grids in one dispatch.
307    ///
308    /// # Parameters
309    /// - `q`: scattering vector per point in `1/Angstrom`, length `n_points`.
310    /// - `stack_of`: stack index per point, each `< n_stacks`.
311    /// - `k0`: vacuum wavenumber per stack in `1/Angstrom`, length `n_stacks`.
312    /// - `layers`: row-major `(n_stacks, n_layers)` layer records.
313    /// - `n_layers`: depth of every stack, at least two.
314    ///
315    /// # Returns
316    /// One `[R_pp, R_ss]` pair per point, in input order.
317    ///
318    /// # Errors
319    /// [`RefloxideError::InvalidShape`] for inconsistent buffer lengths, an
320    /// out-of-range stack index, or a batch exceeding device buffer limits;
321    /// [`RefloxideError::Gpu`] when the readback fails.
322    pub fn reflectivity_points(
323        &self,
324        q: &[f32],
325        stack_of: &[u32],
326        k0: &[f32],
327        layers: &[LayerCoeffs<f32>],
328        n_layers: usize,
329    ) -> Result<Vec<[f32; 2]>> {
330        check_points(q.len(), stack_of, k0.len(), layers.len(), n_layers)?;
331        if q.is_empty() {
332            return Ok(Vec::new());
333        }
334        let records = gpu_layers(layers);
335        let (n_layers_u, n_stacks_u, n_points_u) = (
336            to_u32(n_layers, "n_layers")?,
337            to_u32(k0.len(), "n_stacks")?,
338            to_u32(q.len(), "n_points")?,
339        );
340        self.dispatch(
341            &self.pipeline,
342            q.len(),
343            |row_pitch| {
344                bytemuck::bytes_of(&Params {
345                    n_points: n_points_u,
346                    n_layers: n_layers_u,
347                    n_stacks: n_stacks_u,
348                    row_pitch,
349                })
350                .to_vec()
351            },
352            &[
353                (1, bytemuck::cast_slice(q)),
354                (2, bytemuck::cast_slice(k0)),
355                (3, bytemuck::cast_slice(&records)),
356                (5, bytemuck::cast_slice(stack_of)),
357            ],
358        )
359    }
360
361    /// Single-precision reflectance and directional derivatives for `(q, stack)` points.
362    ///
363    /// Evaluates [`refloxide_tmm::kernel::solve_point_recursive_jvp`] for every
364    /// `(direction, point)` pair in one dispatch. Direction `k` perturbs the
365    /// layer records by `dlayers[k]` and the scattering vectors by `dq[k]`.
366    ///
367    /// # Parameters
368    /// - `q`, `stack_of`, `k0`, `layers`, `n_layers`: as in
369    ///   [`GpuContext::reflectivity_points`].
370    /// - `dq`: row-major `(n_dirs, n_points)` tangent of `q`.
371    /// - `dlayers`: row-major `(n_dirs, n_stacks, n_layers)` tangent records.
372    ///
373    /// # Returns
374    /// Row-major `(n_dirs, n_points)` entries `[R_pp, R_ss, dR_pp, dR_ss]`;
375    /// the value columns repeat for every direction.
376    ///
377    /// # Errors
378    /// As for [`GpuContext::reflectivity_points`], plus
379    /// [`RefloxideError::InvalidShape`] when the tangent buffers do not match.
380    #[allow(clippy::too_many_arguments)]
381    pub fn reflectivity_points_jvp(
382        &self,
383        q: &[f32],
384        stack_of: &[u32],
385        k0: &[f32],
386        layers: &[LayerCoeffs<f32>],
387        n_layers: usize,
388        dq: &[f32],
389        dlayers: &[LayerCoeffs<f32>],
390    ) -> Result<Vec<[f32; 4]>> {
391        check_points(q.len(), stack_of, k0.len(), layers.len(), n_layers)?;
392        if q.is_empty() || dq.is_empty() {
393            return Ok(Vec::new());
394        }
395        if !dq.len().is_multiple_of(q.len()) {
396            return Err(RefloxideError::InvalidShape(format!(
397                "dq length {} is not a multiple of n_points {}",
398                dq.len(),
399                q.len()
400            )));
401        }
402        let n_dirs = dq.len() / q.len();
403        if dlayers.len() != n_dirs * layers.len() {
404            return Err(RefloxideError::InvalidShape(format!(
405                "dlayers length {} != n_dirs ({n_dirs}) * n_stacks * n_layers ({})",
406                dlayers.len(),
407                layers.len()
408            )));
409        }
410        let records = gpu_layers(layers);
411        let d_records = gpu_layers(dlayers);
412        let params = JvpParams {
413            n_points: to_u32(q.len(), "n_points")?,
414            n_layers: to_u32(n_layers, "n_layers")?,
415            n_stacks: to_u32(k0.len(), "n_stacks")?,
416            row_pitch: 0,
417            n_dirs: to_u32(n_dirs, "n_dirs")?,
418            _pad: [0; 3],
419        };
420        self.dispatch(
421            &self.jvp_pipeline,
422            n_dirs * q.len(),
423            |row_pitch| {
424                bytemuck::bytes_of(&JvpParams {
425                    row_pitch,
426                    ..params
427                })
428                .to_vec()
429            },
430            &[
431                (1, bytemuck::cast_slice(q)),
432                (2, bytemuck::cast_slice(k0)),
433                (3, bytemuck::cast_slice(&records)),
434                (5, bytemuck::cast_slice(stack_of)),
435                (6, bytemuck::cast_slice(&d_records)),
436                (7, bytemuck::cast_slice(dq)),
437            ],
438        )
439    }
440
441    /// Double-single (df64) reflectance for independent `(q, stack)` points.
442    ///
443    /// Same contract as [`GpuContext::reflectivity_points`], but inputs stay
444    /// in `f64` and the recursion runs in df64 arithmetic (~48 mantissa
445    /// bits, f32 exponent range), so reflectance tracks the CPU `f64`
446    /// recursion instead of carrying single-precision error. For devices
447    /// without native `f64` shaders (Metal); roughly an order of magnitude
448    /// more ALU work per point than the `f32` kernel.
449    ///
450    /// # Errors
451    /// As for [`GpuContext::reflectivity_points`].
452    pub fn reflectivity_points_df64(
453        &self,
454        q: &[f64],
455        stack_of: &[u32],
456        k0: &[f64],
457        layers: &[LayerCoeffs<f64>],
458        n_layers: usize,
459    ) -> Result<Vec<[f64; 2]>> {
460        check_points(q.len(), stack_of, k0.len(), layers.len(), n_layers)?;
461        if q.is_empty() {
462            return Ok(Vec::new());
463        }
464        let cdf = |z: Complex<f64>| {
465            let (re, im) = (to_df64(z.re), to_df64(z.im));
466            [re[0], re[1], im[0], im[1]]
467        };
468        let records: Vec<GpuLayerDf64> = layers
469            .iter()
470            .map(|l| GpuLayerDf64 {
471                chi_o: cdf(l.chi_o),
472                chi_e: cdf(l.chi_e),
473                thickness: to_df64(l.thickness),
474                sigma: to_df64(l.sigma),
475            })
476            .collect();
477        let qd: Vec<[f32; 2]> = q.iter().map(|&v| to_df64(v)).collect();
478        let k0d: Vec<[f32; 2]> = k0.iter().map(|&v| to_df64(v)).collect();
479        let header = [
480            to_u32(q.len(), "n_points")?,
481            to_u32(n_layers, "n_layers")?,
482            to_u32(k0.len(), "n_stacks")?,
483        ];
484        let out: Vec<[f32; 4]> = self.dispatch(
485            &self.df64_pipeline,
486            q.len(),
487            |row_pitch| {
488                bytemuck::cast_slice(&[header[0], header[1], header[2], row_pitch, 0, 0, 0, 0])
489                    .to_vec()
490            },
491            &[
492                (1, bytemuck::cast_slice(&qd)),
493                (2, bytemuck::cast_slice(&k0d)),
494                (3, bytemuck::cast_slice(&records)),
495                (5, bytemuck::cast_slice(stack_of)),
496            ],
497        )?;
498        let join = |hi: f32, lo: f32| f64::from(hi) + f64::from(lo);
499        Ok(out
500            .iter()
501            .map(|r| [join(r[0], r[1]), join(r[2], r[3])])
502            .collect())
503    }
504
505    /// Reflectance of general dielectric-tensor stacks at independent `(q, stack)` points.
506    ///
507    /// Runs the shader port of [`refloxide_tmm::kernel::solve_point_general`]:
508    /// Berreman eigenmodes of each layer's full susceptibility tensor and the
509    /// 4x4 reflection-matrix recursion with Nevot-Croce roughness. Tilted,
510    /// rotated, and biaxial layers produce cross-polarized reflectance.
511    /// One invocation evaluates one point; inputs and outputs are `f64` on
512    /// the host and are narrowed only for [`GeneralPrecision::F32`].
513    ///
514    /// # Parameters
515    /// - `precision`: shader arithmetic. [`GeneralPrecision::F64`] needs
516    ///   [`GpuContext::supports_f64`]; [`GeneralPrecision::F32`] is a
517    ///   diagnostic build.
518    /// - `q`: scattering vector per point in `1/Angstrom`.
519    /// - `stack_of`: stack index per point, each `< n_stacks`.
520    /// - `k0`: vacuum wavenumber per stack in `1/Angstrom`, positive.
521    /// - `layers`: row-major `(n_stacks, n_layers)`; row 0 of a stack is the
522    ///   isotropic fronting and the last row the backing.
523    /// - `n_layers`: depth of every stack, at least two.
524    ///
525    /// # Returns
526    /// One `[[R_pp, R_sp], [R_ps, R_ss]]` per point (the CPU packing), in
527    /// input order.
528    ///
529    /// # Errors
530    /// [`RefloxideError::Gpu`] when `F64` is requested on an adapter without
531    /// `SHADER_F64`; [`RefloxideError::InvalidShape`] for inconsistent
532    /// buffers or a batch exceeding device limits;
533    /// [`RefloxideError::SingularDynamicMatrix`] (with the point's index
534    /// and stack as `energy_index`) when a layer's mode matrix or the
535    /// recursion denominator is singular.
536    pub fn reflectivity_points_general(
537        &self,
538        precision: GeneralPrecision,
539        q: &[f64],
540        stack_of: &[u32],
541        k0: &[f64],
542        layers: &[GeneralLayer<f64>],
543        n_layers: usize,
544    ) -> Result<Vec<[[f64; 2]; 2]>> {
545        check_points(q.len(), stack_of, k0.len(), layers.len(), n_layers)?;
546        if precision == GeneralPrecision::F64 && !self.has_f64 {
547            return Err(RefloxideError::Gpu(format!(
548                "adapter {} has no native f64 shader support (wgpu SHADER_F64)",
549                self.describe()
550            )));
551        }
552        if q.is_empty() {
553            return Ok(Vec::new());
554        }
555        let pipeline = match precision {
556            GeneralPrecision::F64 => self.general_f64_pipeline.get_or_init(|| {
557                compile_pipeline(
558                    &self.device,
559                    "refloxide-general-f64",
560                    &[GENERAL_F64_WGSL, GENERAL_WGSL].concat(),
561                )
562            }),
563            GeneralPrecision::F32 => self.general_f32_pipeline.get_or_init(|| {
564                compile_pipeline(
565                    &self.device,
566                    "refloxide-general-f32",
567                    &[GENERAL_F32_WGSL, GENERAL_WGSL].concat(),
568                )
569            }),
570        };
571        let mut records = Vec::with_capacity(layers.len() * GENERAL_STRIDE);
572        for l in layers {
573            for row in &l.chi {
574                for c in row {
575                    records.extend([c.re, c.im]);
576                }
577            }
578            records.extend([l.thickness, l.sigma]);
579        }
580        let pack = |values: &[f64]| -> Vec<u8> {
581            match precision {
582                GeneralPrecision::F64 => bytemuck::cast_slice(values).to_vec(),
583                GeneralPrecision::F32 => {
584                    let narrow: Vec<f32> = values.iter().map(|&v| v as f32).collect();
585                    bytemuck::cast_slice(&narrow).to_vec()
586                }
587            }
588        };
589        let header = [
590            to_u32(q.len(), "n_points")?,
591            to_u32(n_layers, "n_layers")?,
592            to_u32(k0.len(), "n_stacks")?,
593        ];
594        let (q_bytes, k0_bytes, record_bytes) = (pack(q), pack(k0), pack(&records));
595        let params = |row_pitch| {
596            bytemuck::cast_slice(&[header[0], header[1], header[2], row_pitch]).to_vec()
597        };
598        let inputs: [(u32, &[u8]); 4] = [
599            (1, &q_bytes),
600            (2, &k0_bytes),
601            (3, &record_bytes),
602            (5, bytemuck::cast_slice(stack_of)),
603        ];
604        let out: Vec<[f64; 4]> = match precision {
605            GeneralPrecision::F64 => {
606                self.dispatch::<[f64; 4]>(pipeline, q.len(), params, &inputs)?
607            }
608            GeneralPrecision::F32 => self
609                .dispatch::<[f32; 4]>(pipeline, q.len(), params, &inputs)?
610                .into_iter()
611                .map(|r| r.map(f64::from))
612                .collect(),
613        };
614        out.iter()
615            .enumerate()
616            .map(|(point, r)| {
617                if r[0] < 0.0 {
618                    Err(RefloxideError::SingularDynamicMatrix {
619                        layer: (-r[0] - 1.0) as usize,
620                        q_index: point,
621                        energy_index: Some(stack_of[point] as usize),
622                    })
623                } else {
624                    Ok([[r[0], r[1]], [r[2], r[3]]])
625                }
626            })
627            .collect()
628    }
629
630    /// Evaluates one df64 operation elementwise on the device.
631    ///
632    /// Diagnostic for new adapters: compares against `f64` on the host to
633    /// confirm that the shader compiler preserves the error-free
634    /// transformations df64 relies on. Inputs are split into `(hi, lo)`
635    /// pairs; results are recombined as `hi + lo`.
636    ///
637    /// # Errors
638    /// [`RefloxideError::InvalidShape`] when `a` and `b` differ in length;
639    /// [`RefloxideError::Gpu`] for device failures.
640    pub fn df64_selftest(&self, a: &[f64], b: &[f64], op: Df64Op) -> Result<Vec<f64>> {
641        if a.len() != b.len() {
642            return Err(RefloxideError::InvalidShape(
643                "df64 selftest inputs differ in length".into(),
644            ));
645        }
646        if a.is_empty() {
647            return Ok(Vec::new());
648        }
649        let da: Vec<[f32; 2]> = a.iter().map(|&x| to_df64(x)).collect();
650        let db: Vec<[f32; 2]> = b.iter().map(|&x| to_df64(x)).collect();
651        let n = to_u32(a.len(), "n")?;
652        let op = op as u32;
653        let out: Vec<[f32; 2]> = self.dispatch(
654            &self.df64_selftest_pipeline,
655            a.len(),
656            |row_pitch| bytemuck::cast_slice(&[n, op, row_pitch, 0u32]).to_vec(),
657            &[
658                (1, bytemuck::cast_slice(&da)),
659                (2, bytemuck::cast_slice(&db)),
660            ],
661        )?;
662        Ok(out
663            .iter()
664            .map(|r| f64::from(r[0]) + f64::from(r[1]))
665            .collect())
666    }
667
668    /// Uploads inputs, runs `threads` invocations of `pipeline`, and reads
669    /// back binding 4 as `threads` values of `O`.
670    fn dispatch<O: Pod>(
671        &self,
672        pipeline: &wgpu::ComputePipeline,
673        threads: usize,
674        params: impl FnOnce(u32) -> Vec<u8>,
675        inputs: &[(u32, &[u8])],
676    ) -> Result<Vec<O>> {
677        let out_bytes = (threads * std::mem::size_of::<O>()) as u64;
678        let max_binding = self.limits.max_storage_buffer_binding_size;
679        let largest = inputs
680            .iter()
681            .map(|(_, b)| b.len() as u64)
682            .chain(std::iter::once(out_bytes))
683            .max()
684            .unwrap_or(0);
685        if largest > max_binding {
686            return Err(RefloxideError::InvalidShape(format!(
687                "batch needs {largest} bytes in one buffer, device binding limit is {max_binding}"
688            )));
689        }
690        let groups = to_u32(threads.div_ceil(WORKGROUP_SIZE as usize), "workgroup count")?;
691        let groups_x = groups.min(self.limits.max_compute_workgroups_per_dimension);
692        let groups_y = groups.div_ceil(groups_x);
693
694        let init = |label: &str, contents: &[u8], usage| {
695            self.device
696                .create_buffer_init(&wgpu::util::BufferInitDescriptor {
697                    label: Some(label),
698                    contents,
699                    usage,
700                })
701        };
702        let params_buf = init(
703            "params",
704            &params(groups_x * WORKGROUP_SIZE),
705            wgpu::BufferUsages::UNIFORM,
706        );
707        let input_bufs: Vec<(u32, wgpu::Buffer)> = inputs
708            .iter()
709            .map(|(binding, bytes)| (*binding, init("input", bytes, wgpu::BufferUsages::STORAGE)))
710            .collect();
711        let out_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
712            label: Some("out"),
713            size: out_bytes,
714            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
715            mapped_at_creation: false,
716        });
717        let read_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
718            label: Some("readback"),
719            size: out_bytes,
720            usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
721            mapped_at_creation: false,
722        });
723
724        let mut entries = vec![
725            wgpu::BindGroupEntry {
726                binding: 0,
727                resource: params_buf.as_entire_binding(),
728            },
729            wgpu::BindGroupEntry {
730                binding: 4,
731                resource: out_buf.as_entire_binding(),
732            },
733        ];
734        entries.extend(
735            input_bufs
736                .iter()
737                .map(|(binding, buf)| wgpu::BindGroupEntry {
738                    binding: *binding,
739                    resource: buf.as_entire_binding(),
740                }),
741        );
742        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
743            label: Some("refloxide"),
744            layout: &pipeline.get_bind_group_layout(0),
745            entries: &entries,
746        });
747
748        let mut encoder = self
749            .device
750            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
751                label: Some("refloxide"),
752            });
753        {
754            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
755                label: Some("refloxide"),
756                timestamp_writes: None,
757            });
758            pass.set_pipeline(pipeline);
759            pass.set_bind_group(0, &bind_group, &[]);
760            pass.dispatch_workgroups(groups_x, groups_y, 1);
761        }
762        encoder.copy_buffer_to_buffer(&out_buf, 0, &read_buf, 0, out_bytes);
763        self.queue.submit(Some(encoder.finish()));
764
765        let (tx, rx) = mpsc::channel();
766        read_buf.map_async(wgpu::MapMode::Read, .., move |res| {
767            let _ = tx.send(res);
768        });
769        self.device
770            .poll(wgpu::PollType::wait_indefinitely())
771            .map_err(|e| RefloxideError::Gpu(format!("device poll failed: {e}")))?;
772        rx.recv()
773            .map_err(|e| RefloxideError::Gpu(format!("readback channel closed: {e}")))?
774            .map_err(|e| RefloxideError::Gpu(format!("readback map failed: {e}")))?;
775        let view = read_buf
776            .get_mapped_range(..)
777            .map_err(|e| RefloxideError::Gpu(format!("readback view failed: {e}")))?;
778        let out: Vec<O> = bytemuck::cast_slice(&view).to_vec();
779        drop(view);
780        read_buf.unmap();
781        Ok(out)
782    }
783}
784
785static SHARED: OnceLock<std::result::Result<GpuContext, String>> = OnceLock::new();
786
787/// Process-wide [`GpuContext`], created on first use and reused thereafter.
788///
789/// # Errors
790/// [`RefloxideError::Gpu`] when device acquisition failed; the failure is
791/// cached so later calls fail fast instead of re-probing adapters.
792pub fn shared_context() -> Result<&'static GpuContext> {
793    SHARED
794        .get_or_init(|| GpuContext::new().map_err(|e| e.to_string()))
795        .as_ref()
796        .map_err(|e| RefloxideError::Gpu(e.clone()))
797}
798
799/// GPU counterpart of [`refloxide_tmm::uniaxial::uniaxial_reflectivity_batch`].
800///
801/// Inputs are validated with the CPU contract, packed into susceptibility
802/// records in `f64`, then explicitly narrowed to `f32` for the device. The
803/// shader evaluates the decoupled uniaxial-z recursion, whose reflectance
804/// agrees with the `f64` 4x4 kernel to about `1e-4` relative in the worst
805/// validated case. Every stack must have the same number of layers.
806///
807/// Transmission is not computed: `tran` has the CPU layout but every entry
808/// is `NaN + NaN i`, so accidental use propagates visibly rather than
809/// silently. Cross-polarized reflectance entries are exactly zero.
810///
811/// # Errors
812/// Shape and energy errors as for the CPU batch kernel,
813/// [`RefloxideError::InvalidShape`] for ragged layer counts, and
814/// [`RefloxideError::Gpu`] for device failures.
815pub fn uniaxial_reflectivity_batch(
816    q: &[f64],
817    layers: &[Vec<Layer>],
818    tensor: &[Vec<Matrix3<Complex<f64>>>],
819    energies_ev: &[f64],
820) -> Result<UniaxialBatchOutput> {
821    validate_batch(layers, tensor, energies_ev)?;
822    let n_e = energies_ev.len();
823    let n_q = q.len();
824    let q_points: Vec<f64> = (0..n_e).flat_map(|_| q.iter().copied()).collect();
825    let stack_of: Vec<usize> = (0..n_e).flat_map(|e| std::iter::repeat_n(e, n_q)).collect();
826    let flat = uniaxial_reflectivity_points(&q_points, &stack_of, layers, tensor, energies_ev)?;
827    let mut refl = flat.refl.into_iter();
828    let mut tran = flat.tran.into_iter();
829    Ok(UniaxialBatchOutput {
830        refl: (0..n_e)
831            .map(|_| refl.by_ref().take(n_q).collect())
832            .collect(),
833        tran: (0..n_e)
834            .map(|_| tran.by_ref().take(n_q).collect())
835            .collect(),
836    })
837}
838
839/// GPU counterpart of [`refloxide_tmm::uniaxial::uniaxial_reflectivity_points`].
840///
841/// Precision, transmission (`NaN`), and cross-polarized (zero) semantics are
842/// those of [`uniaxial_reflectivity_batch`]; every stack must have the same
843/// number of layers. All points run in a single dispatch.
844///
845/// # Errors
846/// Shape and energy errors as for the CPU point kernel,
847/// [`RefloxideError::InvalidShape`] for ragged layer counts, and
848/// [`RefloxideError::Gpu`] for device failures.
849pub fn uniaxial_reflectivity_points(
850    q: &[f64],
851    stack_of: &[usize],
852    layers: &[Vec<Layer>],
853    tensor: &[Vec<Matrix3<Complex<f64>>>],
854    energies_ev: &[f64],
855) -> Result<UniaxialOutput> {
856    validate_points(q, stack_of, layers, tensor, energies_ev)?;
857    let n_layers = layers[0].len();
858    if layers.iter().any(|l| l.len() != n_layers) {
859        return Err(RefloxideError::InvalidShape(
860            "gpu kernels require the same layer count for every stack".into(),
861        ));
862    }
863    let nan = Complex::new(f64::NAN, f64::NAN);
864    let tran = vec![[[nan; 2]; 2]; q.len()];
865    if q.is_empty() {
866        return Ok(UniaxialOutput {
867            refl: Vec::new(),
868            tran,
869        });
870    }
871    let narrow = |z: Complex<f64>| Complex::new(z.re as f32, z.im as f32);
872    let records: Vec<LayerCoeffs<f32>> = layers
873        .iter()
874        .zip(tensor)
875        .flat_map(|(l, t)| layer_coeffs(l, t))
876        .map(|c| LayerCoeffs {
877            chi_o: narrow(c.chi_o),
878            chi_e: narrow(c.chi_e),
879            thickness: c.thickness as f32,
880            sigma: c.sigma as f32,
881        })
882        .collect();
883    let q32: Vec<f32> = q.iter().map(|&v| v as f32).collect();
884    let k0: Vec<f32> = energies_ev.iter().map(|&e| wavenumber(e) as f32).collect();
885    let stack32 = stack_of
886        .iter()
887        .map(|&s| u32::try_from(s))
888        .collect::<std::result::Result<Vec<u32>, _>>()
889        .map_err(|_| RefloxideError::InvalidShape("stack index exceeds u32".into()))?;
890
891    let out = shared_context()?.reflectivity_points(&q32, &stack32, &k0, &records, n_layers)?;
892    let refl = out
893        .iter()
894        .map(|r| [[f64::from(r[0]), 0.0], [0.0, f64::from(r[1])]])
895        .collect();
896    Ok(UniaxialOutput { refl, tran })
897}
898
899/// GPU counterpart of [`refloxide_tmm::uniaxial::uniaxial_reflectivity_points_jvp`].
900///
901/// Values and tangents are narrowed to `f32` on the device; derivatives are
902/// forward-mode exact for the single-precision recursion, so their relative
903/// accuracy matches the reflectance (about `1e-4` worst case) instead of
904/// suffering finite-difference cancellation. All `(direction, point)` pairs
905/// run in one dispatch. Every stack must have the same number of layers.
906///
907/// # Errors
908/// As for the CPU JVP kernel, [`RefloxideError::InvalidShape`] for ragged
909/// layer counts, and [`RefloxideError::Gpu`] for device failures.
910pub fn uniaxial_reflectivity_points_jvp(
911    q: &[f64],
912    stack_of: &[usize],
913    layers: &[Vec<Layer>],
914    tensor: &[Vec<Matrix3<Complex<f64>>>],
915    energies_ev: &[f64],
916    tangents: &PointsTangents,
917) -> Result<PointsJvpOutput> {
918    let (coeffs, dcoeffs) = jvp_coeffs(q, stack_of, layers, tensor, energies_ev, tangents)?;
919    let n_layers = layers[0].len();
920    if layers.iter().any(|l| l.len() != n_layers) {
921        return Err(RefloxideError::InvalidShape(
922            "gpu kernels require the same layer count for every stack".into(),
923        ));
924    }
925    let n_points = q.len();
926    let n_dirs = tangents.dq.len();
927    if n_points == 0 || n_dirs == 0 {
928        let refl = uniaxial_reflectivity_points(q, stack_of, layers, tensor, energies_ev)?
929            .refl
930            .iter()
931            .map(|r| [r[0][0], r[1][1]])
932            .collect();
933        return Ok(PointsJvpOutput {
934            refl,
935            jac: Vec::new(),
936        });
937    }
938    let narrow = |c: &LayerCoeffs<f64>| LayerCoeffs {
939        chi_o: Complex::new(c.chi_o.re as f32, c.chi_o.im as f32),
940        chi_e: Complex::new(c.chi_e.re as f32, c.chi_e.im as f32),
941        thickness: c.thickness as f32,
942        sigma: c.sigma as f32,
943    };
944    let records: Vec<LayerCoeffs<f32>> = coeffs.iter().flatten().map(narrow).collect();
945    let d_records: Vec<LayerCoeffs<f32>> = dcoeffs.iter().flatten().flatten().map(narrow).collect();
946    let q32: Vec<f32> = q.iter().map(|&v| v as f32).collect();
947    let dq32: Vec<f32> = tangents.dq.iter().flatten().map(|&v| v as f32).collect();
948    let k0: Vec<f32> = energies_ev.iter().map(|&e| wavenumber(e) as f32).collect();
949    let stack32 = stack_of
950        .iter()
951        .map(|&s| u32::try_from(s))
952        .collect::<std::result::Result<Vec<u32>, _>>()
953        .map_err(|_| RefloxideError::InvalidShape("stack index exceeds u32".into()))?;
954    let out = shared_context()?
955        .reflectivity_points_jvp(&q32, &stack32, &k0, &records, n_layers, &dq32, &d_records)?;
956    Ok(PointsJvpOutput {
957        refl: out[..n_points]
958            .iter()
959            .map(|r| [f64::from(r[0]), f64::from(r[1])])
960            .collect(),
961        jac: out
962            .iter()
963            .map(|r| [f64::from(r[2]), f64::from(r[3])])
964            .collect(),
965    })
966}