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, batch_grad=nothing, retain=nothing)
LogTarget(logdensity; grad=nothing, batch=nothing, batch_grad=nothing, retain=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
Batch values and gradientsbatch_grad!(values, gradients, samples)batch_grad!(values, gradients, samples, p)Optional combined derivative callback

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. values[j] corresponds to sample j (column j for vector parameters). Retained sampling batches preserve this order in the result, including with a ProposalBank. AMIS concatenates these batches in round order. Do not concatenate every callback invocation: adaptation trials, upper MCMC evaluations, and padded candidates need not appear in the result.

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.

Pass batch_grad=batch_grad! for combined accelerator values and gradients, taking priority over scalar gradients and AD in accelerator score phases. The callback fills values and gradients for independent columns of samples. It takes an optional final context p, like batch. On CPU, grad or adtype remains preferred. Without either, CPU workers call batch_grad on one-column batches; this fallback requires a thread-safe callback or threaded=false. Accept views and varying positive widths. The return value is ignored. Write every value and every gradient at finite-density points. Return -Inf safely outside support; the corresponding gradient is ignored. Do not throw only because one column lies outside support. Never mix columns or normalize their joint density. Inputs are read-only and outputs are borrowed. With named transforms, both sample and gradient batches have logical fields; the package adds Jacobians and pulls gradients back to sampling coordinates. Named mapping checks can synchronize once per batch. Flat batches require no per-gradient host readback. batch remains separate for value-only phases.

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.

Pass retain=RetainCoordinates(...) to save an expensive parameter map during returned importance draws. Trial and derivative evaluations keep the ordinary callable. See RetainCoordinates for the output-buffer contract.

source
ImportanceSamplers.RetainCoordinates — Type
RetainCoordinates(evaluate, sample; batch=nothing)

Retain mapped coordinates during importance draws. Pass this configuration as LogTarget(f; retain=...). sample specifies the mapped sample shape and names. Scalar types are inferred from evaluate for the actual input and context, without evaluating the target. Only the shape is stored; prototype arrays are not copied to accelerators. Mapped numeric leaves and the Jacobian must have inferable concrete types.

evaluate(z) (or evaluate(z, p) with target context) returns (logtarget, x, logabsdet). Its log target must equal f(z). logabsdet is log|dx/dz|, relative to the logical coordinates supplied to the callback. An engine transform= adds its Jacobian to both the saved log target and saved map Jacobian. Derivatives, MCMC and adaptation trials use f, not this callback. Target values are retained automatically.

The optional batch callback is batch!(values, coordinates, logjacobians, samples[, p]). Fill every output column. Inputs are read-only and all buffers are borrowed. Keep device data resident, as for LogTarget's ordinary batch callback.

Results expose retained = (; coordinates, logjacobians). Their restored log densities are result.logtargets - result.retained.logjacobians. These arrays are independent of input views, callback scratch and later sampler runs.

source

Preparation and execution

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

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

Set save_logtargets=true to retain the exact target log densities used in weight construction in result.logtargets, aligned with the samples. Values are in sampling coordinates: transform= includes its forward log Jacobian, even when returned samples use logical coordinates. No target is evaluated again to fill this vector. Each result owns its vector on the sampling device; the default stores nothing and adds no sample-sized storage or execution work.

An optional QuadraticCoupling maps latent vectors to physical vectors. A 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. Named layouts give the target 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

Prefer a native PureRNGs generator. Preparation preserves its key and position. An explicit Random.AbstractRNG supplies one UInt64 seed for a new PureRNGs.Philox4x32 stream. There is no default RNG. Read the continued stream through current_rng. Reusing the same input snapshot repeats its stream. 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,
                  save_logtargets=false)
importance_sample(rng, logtarget, p, algorithm;
                  transform=nothing, factor_execution=nothing, threaded=true,
                  save_logtargets=false)

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. Native snapshots support Statistics.mean, var, std, and cov; use proposal_scale_factor to read a Gaussian or Student-t scale factor. These accessors do not change the sampler or add a Distributions.jl dependency.

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.

Prefer a native PureRNGs generator or a compatible Reactant stream snapshot. The returned sampler advances that stream without reseeding. Equal snapshots do not produce independent streams. An explicit Random.AbstractRNG seeds a new stream once, as in prepare_sampler.

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