Devices

Prepare on CPU, then apply an explicit MLDataDevices device to the complete sampler. The target data, proposal, random buffers, and adaptation state move together.

Prepared state

using ImportanceSamplers, PureRNGs, Statisticsimport MLDataDevicesfunction logtarget(x, p)    value = zero(eltype(x))    for i in eachindex(x)        value -= abs2(x[i] - p.centre[i]) / 2    end    return valueendp = (; centre=Float32[0.25, -0.5, 0.75])algorithm = ImportanceSampling(    SphericalGaussian(zeros(Float32, 3), 1.5f0);    nsamples=10_000,)prepared = prepare_sampler(Threefry4x32(42), logtarget, p, algorithm)

This example chooses Float32 so its numerical setup also works on Metal. CPU and CUDA also support Float64. The package does not require every model to use one precision.

Numerical data is passed through p, not captured by the target function.

CUDA

With CUDA.jl installed:

using CUDACUDA.allowscalar(false)device = MLDataDevices.with_eltype(MLDataDevices.CUDADevice(), nothing)gpu_sampler = prepared |> devicegpu_samples = importance_sample!(gpu_sampler)gpu_mean = mean(gpu_samples)host_samples = MLDataDevices.CPUDevice()(gpu_samples)

device(prepared) and prepared |> device are equivalent. The nothing element-type policy preserves the supplied precision. A device with unspecified scalar policy is rejected.

To select another physical CUDA device explicitly:

physical = collect(CUDA.devices())[2]device = MLDataDevices.CUDADevice{typeof(physical),Nothing}(physical)

Array summaries remain on the GPU. host_samples is an explicit, independent CPU copy.

Metal

Use the same numerical setup, with Metal installed:

using MetalMetal.allowscalar(false)device = MLDataDevices.MetalDevice{Float32}()metal_sampler = device(prepared)metal_samples = importance_sample!(metal_sampler)host_samples = MLDataDevices.CPUDevice()(metal_samples)

Metal uses Float32. The explicit device policy may convert supplied floating-point state. Constructing the whole model in Float32 makes that choice visible from the start.

Reactant

For the checked NVIDIA GPU path, install Reactant and CUDA:

using CUDA, ReactantReactant.set_default_backend("gpu")device = MLDataDevices.with_eltype(MLDataDevices.ReactantDevice(), nothing)compiled_sampler = device(prepared)compiled_samples = importance_sample!(compiled_sampler)host_samples = MLDataDevices.CPUDevice()(compiled_samples)

CUDA is needed for Reactant's KernelAbstractions integration, including its CPU path. Native CPU sampling itself has no CUDA dependency.

Device preparation compiles the built-in numerical phases. Later calls reuse those executables with the current RNG and adapted proposals. Preparation can therefore cost much more than one warmed run.

Backend support

These entries describe implemented paths with representative hardware checks. They do not imply that every user target compiles on every backend.

BackendNative sampler scopeMain limits
Ordinary CPUAll methods, plus generic proposals where the method permits themFloat32/Float64 log densities
Native CUDASupported native proposal/method combinations belowDevice-compatible target and gradient operations
MetalSupported native proposal/method combinations belowFloat32, explicit GRAMIS gradient
Reactant GPUBuilt-in compiled paths, including batch targetsTraceable operations and fixed prepared schedules
Reactant CPUPlain/static IS, supported AMIS/NPMC, global DM-PMC, and built-in LAIS casesPreflight restrictions listed below
AMDGPUNot validated or claimedA KernelAbstractions backend alone does not supply full package support

Gaussian and Student-t proposals support every method, subject to backend limits. HMC-driven LAIS and HAIS require vector layouts and currently support ordinary CPU and native CUDA. Metal and Reactant HMC paths reject explicitly during setup. Boxes support fixed IS/static MIS. Independent Gamma and Laplace also support AMIS/N-PMC marginal moment adaptation and DM-PMC/APIS mean adaptation. Laplace also supports LAIS lower proposals. Gamma retains coordinate variance; Laplace retains scales in these population methods. On Reactant CPU these independent families support scalar and vector layouts; Gaussian/Student-t moment fits remain scalar-only.

Reactant CPU rejects GRAMIS, APIS, CAIS, locally resampled DM-PMC, factor-proposal AMIS/NPMC, and LAIS-SMH during preflight. Their cooperative kernels hit an upstream CPU-lowering limit. Active RAM tuning also fails CPU lowering and is rejected, including batch targets. RAM with WarmupTuning(0) avoids the tuning kernels. Use MLDataDevices.CPUDevice() for ordinary CPU execution.

Reactant CPU can flush subnormal floating-point values to zero, including tiny normalized weights. Selecting Float64 does not change that backend behavior. Use ordinary CPU execution when gradual underflow matters for weighted moments.

Reactant GPU has checked factor Student-t paths for static MIS, AMIS, NPMC, DM-PMC, APIS, CAIS, and all three LAIS transitions. Those checks do not establish Student-t GRAMIS support on Reactant.

Native CUDA supports supplied gradients and supported Enzyme reverse-mode gradients. Metal requires supplied gradients. See Gradients for the exact interface.

Plain and static MIS support same-precision Gaussian ProductProposal blocks on accelerators, preserving names and within-block covariance. Correlated products keep blockwise CPU execution where available and become dense native proposals during explicit device transfer. Compatible named product banks share one field layout and transform specification. Other generic products remain CPU-only. Native transform= layouts can expose named, bounded, positive, and simplex parameters. Do not infer bank support from a standalone transformed proposal.

Residency and transfers

psis has native CPU and CUDA checks in Float32 and Float64. Its weights, sorting, and Pareto fit stay on the selected device. Only scalar diagnostics reach the host. Metal, AMDGPU, and Reactant PSIS paths are not yet validated or claimed. Transfer a result explicitly to ordinary CPU before smoothing on an unvalidated backend.

Samples, log weights, proposal state, and numerical workspaces remain on the device. Bounded failure and round summaries can synchronize with the host. A batch callback can also require synchronization.

Scalar indexing, iteration, quantiles, and medians require an explicit CPU result transfer. Device moments, scalar functionals, normalization, slicing, and resampling have resident paths. Reactant scalar summaries remain Reactant numbers until explicitly converted.

Apply device transfer before the source sampler's first execution. Transfer creates a distinct handle and leaves the CPU source usable. An accelerator-prepared sampler cannot itself migrate to another device or back to CPU.

Use current_proposal(MLDataDevices.CPUDevice(), sampler) for a proposal snapshot. Use retarget to rebuild target-dependent state on the same device.

All backends use a native PureRNGs generator. Transfer preserves its generator family, key, and position without consuming a replacement seed. The source and transferred handles start from the same snapshot. Split the RNG explicitly for independent runs. Normal draws and floating-point reductions need not agree bitwise across devices.

State containers

Named tuples already support recursive device conversion. Custom context or callable structs with arrays need a standard Adapt.adapt_structure rule.

Do not capture host arrays in opaque closures or rely on global arrays. The sampler cannot reliably transfer those arrays. Pass them explicitly through p.

There is no silent CPU fallback for an unsupported device contract. The exception's reason identifies the rejected capability.

References