API reference

The tutorials explain complete workflows. This section lists signatures and exact contracts for lookup.

Targets

ImportanceSamplers.LogTarget — Type
LogTarget(logdensity)
LogTarget(logdensity, adtype; grad=nothing, batch=nothing)
LogTarget(logdensity; grad=nothing, batch=nothing)

Mark logdensity as a package callable target.

This explicit wrapper takes priority over target interfaces advertised by the wrapped object. The callable must accept logdensity(sample) in the context-free API or logdensity(sample, p) when an explicit context is passed, and must return a Float32 or Float64 unnormalized log density. For CUDA, use a device-compatible callable and pass numerical arrays through p; opaque closure captures cannot be transferred reliably.

CallableWithout contextWith context pRequirement
Log targetlogdensity(sample)logdensity(sample, p)Always required, including with batch
Batch valuesbatch!(values, samples)batch!(values, samples, p)Optional; fill every value
In-place gradientgrad!(g, sample)grad!(g, sample, p)Optional explicit derivative
Out-of-place gradientgrad(sample)grad(sample, p)CPU-only alternative to an in-place gradient

Pass one gradient form through grad= or select an automatic backend through adtype. Only gradient-based methods such as FirstOrderGRAMIS need derivatives. An explicit gradient takes priority over automatic differentiation.

Pass batch=batch! to evaluate independent samples together. The callback is batch!(values, samples) or batch!(values, samples, p) with explicit context. Fill every entry of values with the corresponding scalar log density. Its return value is ignored. Samples are a vector for scalar parameters, a dimension-by-count matrix for vector parameters, or a named tuple of batch leaves for named parameters. With transform=, leaves contain logical values and the package adds the Jacobian. Batch widths can change, but never equal zero.

Inputs are borrowed and read-only. Retain neither inputs nor output buffers. Each value must be independent of batch width and other samples. -Inf is valid, but NaN and +Inf fail the run. The callback controls CPU parallelism. On an accelerator, inputs, outputs, and p stay resident. Use the current task's device stream or complete private-stream work before returning. Failure checks can synchronize at batch boundaries, never once per sample. Without batch, scalar execution remains unchanged. Custom MCMC transitions control how they evaluate their target. Reactant supports fixed-width batch phases, including FirstOrderGRAMIS through padded backtracking batches. Inactive candidates keep their accepted locations; their new target values are discarded and their evaluation cost is recorded.

An explicit grad takes priority over adtype. CPU automatic gradients use DifferentiationInterface. FirstOrderGRAMIS also supports reverse-mode ADTypes.AutoEnzyme() on CUDA when Enzyme is loaded. It batches the existing scalar logdensity callable internally; p remains constant during differentiation. The callable and its operations must support Enzyme's device differentiation. Structured GPU contexts can require Enzyme's runtime-activity mode; the supplied AD mode is preserved, not changed implicitly. The Reactant extension also supports compiled gradients for compatible targets. Native Metal requires explicit gradients. Out-of-place explicit gradients are CPU-only. See the device guide for backend-specific limits. batch changes value evaluation only. Automatic differentiation still uses the scalar callable and can evaluate its primal while computing a gradient.

With a named transform= layout, the callable receives named logical parameters. An explicit gradient differentiates only this logical target. Write scalar gradient fields with g.field[] and vector fields with g.field[i]. The package adds the transform pullback and Jacobian derivative. Borrowed inputs and gradient buffers must not escape the callback. CPU automatic gradients use ordinary arrays in the composed target through DifferentiationInterface.

source

Preparation and execution

ImportanceSamplers.prepare_sampler — Function
prepare_sampler(rng, logtarget, algorithm;
                transform=nothing, factor_execution=nothing, threaded=true)
prepare_sampler(rng, logtarget, p, algorithm;
                transform=nothing, factor_execution=nothing, threaded=true)

Bind a target, optional context p, algorithm, CPU execution policy, and RNG into a reusable prepared sampler.

An optional named transform uses complete, disjoint flat selectors such as (weights=(1:2=>SimplexTransform(3)), scale=(3=>PositiveTransform())). A bare index or range, such as offset=4, means an identity transform. The target receives named logical parameters. The sampler keeps numerical coordinates internally and includes the forward log Jacobian in raw weights. Returned named arrays retain the original weights and provenance. Names do not impose proposal independence. Existing behavior is unchanged when omitted.

Known target interfaces and known LogDensityProblems dimensions are resolved during preparation. Callable applicability and scalar log-density types are validated on the first retained execution, when the logical sample type is available. The target must return a Float32 or Float64 log density.

Choose one target interface, not every row. Without explicit context, resolution prefers LogDensityProblems, then DensityInterface, then callable semantics. LogTarget selects callable semantics explicitly. Passing p also selects the two-argument callable form.

Target formRequired operationsOptional operations
Callablelogtarget(sample) or logtarget(sample, p)Batch and gradient callbacks through LogTarget
DensityInterface objectDensityInterface.DensityKind(target) advertising a density, and DensityInterface.logdensityof(target, sample)None required
LogDensityProblems objectLogDensityProblems.capabilities, LogDensityProblems.dimension, and LogDensityProblems.logdensityFirst-order capability and LogDensityProblems.logdensity_and_gradient for gradient methods

The prepared sampler retains and advances the supplied RNG. Do not consume that RNG elsewhere while using the sampler. A prepared sampler is mutable and non-reentrant. Repeated calls to importance_sample! create separate, noncumulative results with separate arrays.

Preparation always produces a CPU sampler. Apply an explicit MLDataDevices.AbstractDevice value to the complete prepared sampler before its first execution to request transfer. Transfer recursively moves proposal, device-adaptable callable state, and every numerical array in p; opaque closure captures cannot be moved reliably and are rejected for accelerator execution. An accelerator whose public eltype(device) is Missing is rejected as :scalar_policy_unspecified; construct a preserving device with an explicit non-Missing scalar policy. The accelerator guide shows CUDA construction for the current or a selected physical device without auto-selection. Native CUDA execution requires threaded=true and keeps returned arrays on the device. Set threaded=false for serial CPU evaluation. On CPU, threaded=true falls back to serial execution when Julia has one default thread; accelerator launch policy does not depend on host thread count. The default factor path is fused on CPU and batched on accelerators that support factor batching. Use FusedFactorExecution or BatchedFactorExecution to override that choice; unsupported batched cases use the fused path. Native Gaussian MIS with wider logweights supports explicit batching without narrowing those weights. Its default remains fused; explicit batching uses a separate denominator buffer in the logweight precision.

source
ImportanceSamplers.importance_sample — Function
importance_sample(rng, logtarget, algorithm;
                  transform=nothing, factor_execution=nothing, threaded=true)
importance_sample(rng, logtarget, p, algorithm;
                  transform=nothing, factor_execution=nothing, threaded=true)

Run one complete importance-sampling estimator.

This is the one-shot form of prepare_sampler followed by importance_sample!. logtarget returns a log density, not a linear density. The contextual overload calls logtarget(sample, p). The one-shot form executes on CPU; apply a device to a prepared sampler for CUDA execution. The optional named transform follows prepare_sampler, including the forward Jacobian and named returned samples.

The result stores the algorithm's canonical raw log weights. Use normalized_weights for weights that sum to one and lognormalizer for the complete estimator's log normalizer.

source
ImportanceSamplers.importance_sample! — Function
importance_sample!(sampler)

Execute one complete estimator run using a prepared sampler.

The bang records that the sampler's RNG stream and running state are mutated. It also permanently fixes device placement when execution begins, whether the run succeeds or fails. Each returned WeightedSamples has separate storage and cannot be changed by later runs. Concurrent use of one sampler is unsupported; use separate prepared samplers and RNGs. An entry that observes the sampler already busy, including recursive re-entry, throws SamplerBusyError; this check does not synchronize simultaneous callers. CUDA results remain device-resident until an explicit transfer such as result |> MLDataDevices.cpu_device().

source

Learned state

ImportanceSamplers.current_proposal — Function
current_proposal(sampler)
current_proposal(destination, sampler)

Return an independent snapshot of the proposal population currently stored by a CPU-prepared DeterministicMixturePMC sampler. Active proposals use the latest adapted means. Gaussian, Student-t and Laplace scales or factors remain fixed. Gamma retains its configured coordinate variance. Masses stay fixed. Inert zero-mass proposals retain their configured positions and stable IDs.

The returned ProposalBank does not alias the sampler. The one-argument form is CPU-only and never hides a device transfer. For an accelerator-prepared sampler, pass an explicit preserving CPU destination: current_proposal(MLDataDevices.cpu_device(), sampler). That form copies only the current packed locations and stable proposal IDs under the sampler's physical-device scope; it does not migrate the prepared sampler, RNG, workspaces, target, or result storage. Scalar-converting and non-CPU destinations are rejected. APIS uses the same population snapshot and transfer contract.

source
current_proposal(sampler)

Return an independent snapshot of the proposal committed by a CPU-prepared AMIS or NPMC sampler. For an accelerator-prepared sampler, pass an explicit preserving CPU destination. A successful call commits its final fitted proposal for the next call; a failed call leaves this snapshot unchanged.

source
current_proposal(destination, sampler)

Copy the committed AMIS or NPMC proposal to an explicit preserving CPU device. This transfers the proposal parameters, not the sample history.

source
current_proposal(sampler)
current_proposal(destination, sampler)

Return an independent ProposalBank of dense FactorGaussian or FactorStudentT snapshots from the population committed by a prepared FirstOrderGRAMIS sampler. Configured masses and stable proposal IDs are preserved. The returned locations, factors, log normalizers, proposal vector, and masses do not alias the sampler's committed or scratch arrays.

The one-argument form is CPU-only and never hides a device transfer. For an accelerator-prepared sampler, pass an explicit preserving CPU destination such as MLDataDevices.cpu_device(). Scalar-converting and non-CPU destinations are rejected. Only committed locations, factors, log normalizers, and stable IDs are copied from accelerator state.

source
ImportanceSamplers.retarget — Function
retarget(rng, sampler, logtarget)
retarget(rng, sampler, logtarget, p)

Warm-start a new target from an adaptive sampler's committed proposal.

The returned sampler preserves the source algorithm's round schedule, mathematical controls, threading policy, factor execution policy, and device. It starts a fresh RNG stream and rebuilds target binding, derivative state, adaptation history, workspaces, diagnostics, and failure buffers. Samples, weights, and normalizer state from the source are never reused. The source sampler remains unchanged and usable.

On CPU, the returned sampler retains and advances the supplied RNG. Accelerator setup consumes one UInt64 after preflight to seed a separate backend RNG. A later backend RNG construction failure can therefore consume that value. The supplied RNG must differ from the source sampler's RNG.

Retargeting supports prepared DeterministicMixturePMC, APIS, CAIS, NPMC, LAIS, AMIS, and FirstOrderGRAMIS samplers. LAIS retains learned transition factors but resets current-target caches and tuning progress, including warmup, for the new target. Plain and static importance sampling have no learned proposal state; call prepare_sampler with their algorithm instead. Accelerator retargeting stages the committed proposal in CPU memory, allocates fresh CPU workspaces, and transfers the complete new sampler to the source device. Target support coverage is a caller precondition because it cannot be proven for an arbitrary callable. Normal preparation still checks known target dimensions, callable contracts, and method constraints.

source