Samplers and transitions

See Method comparison for adaptation, weighting, and allocation requirements.

Algorithm configurations

ImportanceSamplers.ImportanceSampling — Type
ImportanceSampling(proposal; nsamples)
ImportanceSampling(bank::ProposalBank; nsamples, mis_scheme=StratifiedMixture())

Configure plain or static multiple importance sampling.

Generic CPU proposals need one draw operation and the normalized density for the same measure.

OperationRequirement
PureRNGs.rand_next(rng, proposal)Return (sample, next_rng). Samples must have a consistent scalar, vector, or named-tuple layout and leaf types
DensityInterface.logdensityof(proposal, sample)Return the normalized log density of the draw law

nsamples must be a positive Int and is the exact number of samples returned by every run. Generic proposals execute on CPU; supported native proposals also support prepared accelerator execution. Loading Distributions.jl adds native conversion for Uniform, Gamma, Normal, conventional MvNormal, and supported Student-t forms. Native proposals include SphericalGaussian, DiagonalGaussian, FactorGaussian, SphericalStudentT, DiagonalStudentT, FactorStudentT, BoxUniform, IndependentGamma, and IndependentLaplace.

When the first argument is a ProposalBank, mis_scheme selects one of the four complete assignment/denominator contracts described by AbstractMISScheme; it defaults to StratifiedMixture. The result stores canonical raw log weights and stable one-based generating proposal IDs in result.provenance.proposal_id. Bank capabilities are validated during preparation, before the supplied RNG is consumed. With a batch target, callback sample order matches result.samples, including when sampling from a proposal bank.

source
ImportanceSamplers.AMIS — Type
AMIS(proposal; rounds, round_size)

Configure adaptive multiple importance sampling with a fixed round schedule. proposal must be a native Float32 or Float64 scalar spherical, vector spherical, diagonal, or factor Gaussian or Student-t, or an independent Gamma or Laplace proposal. Independent families fit marginal moments without a covariance ridge or correlations; invalid fits fail rather than being clipped. Student-t fits require nu > 2, keep nu fixed, and convert fitted covariance to Student-t scale. Loading Distributions.jl accepts its supported normal, Student-t, Gamma and Laplace forms through native conversion. round_size is either one positive Int repeated for every round or a positive Vector{Int} with one entry per round.

Result samples concatenate newly drawn batches in round order, preserving the sample order within each batch. Earlier target values are cached, not reevaluated. Each successful result reports diagnostics.method == :amis. diagnostics.round_ess[t] and diagnostics.round_lognormalizers[t] summarize all samples retained through round t using their retrospective weights after that round. Each round log normalizer is a numerical estimate; no finite-sample unbiasedness or generic consistency guarantee is claimed.

source
ImportanceSamplers.NPMC — Type
NPMC(proposal; rounds, round_size)

Configure nonlinear population Monte Carlo with a native scalar or vector Gaussian, Student-t, independent Gamma or independent Laplace proposal and a fixed round schedule, as accepted by AMIS. Each round fits moments using weights clipped at the isqrt(n)-th largest weight, where n is the round size. Gaussian/Student-t fits add the same scale-aware covariance ridge as AMIS. Independent families fit marginal moments without a ridge and reject degenerate or unrepresentable parameters. Student-t fits require nu > 2, retain nu, and convert covariance to Student-t scale before publication.

Returned samples retain their raw logtarget - logproposal weights and round provenance. This is the N-PMC adaptation variant, not the original paper's transformed-weight estimator. diagnostics.round_ess and diagnostics.round_lognormalizers summarize each round's raw weights. diagnostics.adaptation_ess summarizes the clipped weights used for fitting. The final fitted proposal persists after a successful call. A failed call retains the last committed proposal and throws NPMCRoundError.

source
ImportanceSamplers.DeterministicMixturePMC — Type
DeterministicMixturePMC(
    bank;
    rounds,
    round_size,
    resampling=GlobalResampling(),
)

Configure deterministic-mixture population Monte Carlo with a fixed round schedule. round_size is either one positive Int repeated for every round or a positive Vector{Int} with one entry per round. resampling selects global or local ancestor selection while keeping the same deterministic-mixture weights.

Native Gaussian, Student-t and independent Laplace populations change locations and preserve each scale and positive Student-t degrees of freedom. Independent Gamma populations resample means at fixed coordinate variance, updating both shape and scale. Each bank uses one family.

source
ImportanceSamplers.APIS — Type
APIS(bank; rounds, round_size)

Configure adaptive population importance sampling with a fixed Gaussian, Student-t, independent Laplace or independent Gamma proposal population. Gaussian, Student-t and Laplace scales stay fixed. Gamma uses the mean/variance parameterization and retains each coordinate variance while adapting its mean. Student-t also retains each positive nu. A bank uses one family. Each round is one APIS epoch. round_size is the total number of samples in an epoch and may be a positive Int or a vector with one entry per epoch.

APIS requires equal positive proposal masses, equal allocation within every epoch, and at least two samples per proposal. It updates proposal centres after each epoch while retaining Gaussian/Student-t/Laplace scales or Gamma variances.

source
ImportanceSamplers.CAIS — Type
CAIS(bank; rounds, round_size, covariance_ess_threshold=nothing)

Configure canonical covariance-adaptive importance sampling for an equally weighted population of native Gaussian or Student-t proposals. Student-t fits require nu > 2, retain each component's nu, and convert fitted covariance to Student-t scale. Each bank must use one radial family. round_size is the total sample count in each round and may be a positive Int or a Vector{Int} with one entry per round.

Every proposal receives the same number of samples. If covariance_ess_threshold is nothing, the package uses max(d + 1, ceil(Int, 0.3m)) for dimension d and local count m; this is a package default, not a default specified by the CAIS paper. An explicit real threshold must satisfy d < threshold < m in every round.

source
ImportanceSamplers.LAIS — Type
LAIS(bank; transition, rounds, round_size, adapt_scales=false)

Configure layered importance sampling. Each round advances the upper MCMC chains, then draws equally from the lower Gaussian, Student-t or independent Laplace proposals at their new centres. Use current-round deterministic-mixture weights and retain all lower samples.

Independent RandomWalkMetropolis/RAM chains implement PI-MAIS-style upper adaptation. SampleMetropolisHastings instead makes interacting population replacements for I²-MAIS while retaining the same LAIS result and lower-weighting API.

round_size is the total lower count per round, either an integer or a vector with one entry per round. It must divide equally across positive, equal-mass proposals. Each bank uses one translation family. Lower scales and Student-t degrees of freedom stay fixed by default and independent of transition; every positive nu is allowed. With adapt_scales=true, fit marginal widths from local DM-weighted lower draws after each round. Blend old and fitted marginal variance equally, preserving factor correlations. Student-t adaptation requires nu > 2. Degenerate local fits retain the old widths. This optional extension does not adapt the upper transition or its mass matrix. See Width adaptation.

source
ImportanceSamplers.HAIS — Type
HAIS(bank; transition, rounds, round_size, adapt_scales=false)

Configure Hamiltonian adaptive importance sampling with a fixed native Gaussian, Student-t, or independent Laplace population and a HamiltonianMonteCarlo transition. Each round draws and weights lower samples before moving the upper centres and selecting their ancestors independently with replacement.

Lower samples use the normalized current-round deterministic mixture. Cooperation uses pointwise target-to-old-mixture ratios only as adaptation scores: HMC endpoints need not follow that mixture, and cooperation is not target invariant. The final adapted bank is retained even though it generated no returned draw. Student-t degrees of freedom and destination proposal IDs remain fixed. Scales remain fixed unless adapt_scales=true enables the marginal-width extension described under Width adaptation. Widths update after cooperation, using each destination's generating group, not its ancestor.

round_size is a positive Int or one positive entry per round in a Vector{Int}. Every round allocates equally across equal, positive-mass proposals. Optional HMC warmup runs once before the first lower round and performs no cooperation.

source
ImportanceSamplers.FirstOrderGRAMIS — Type
FirstOrderGRAMIS(bank; rounds, round_size, repulsion_strength,
                 covariance_ess_threshold=nothing, covariance_rate=1,
                 covariance_regularization=nothing,
                 tempering_tolerance=1e-4,
                 tempering_max_iterations=16, repulsion_softening=1,
                 max_backtracking_trials=20)

Configure the package's first-order GRAMIS-CAIS hybrid for a fixed population of at least two equally weighted native Gaussian or Student-t proposals. Student-t fits require nu > 2 and retain each nu. Preconditioning, repulsion, blending, and regularization use actual covariance, then fitted factors convert to Student-t scale. Each bank uses one radial family. Spherical, diagonal, and factor forms may be mixed when they share one positive dimension and one Float32 or Float64 scalar type. Initial means must be distinct. Preparation canonicalizes every proposal to a dense lower-factor representation while preserving configured masses and stable proposal IDs.

round_size is the total sample count in each round and may be one positive integer or a positive integer vector with one entry per round. Balanced deterministic allocation requires at least d + 2 samples from every proposal in every round. repulsion_strength and covariance_rate accept a scalar, per-round vector, or callable round -> value; schedules restart at round one for each sampling call. Repulsion strength must be finite and nonnegative, and each covariance rate must satisfy 0 < rate <= 1.

covariance_ess_threshold may be nothing, an absolute integer, a fraction in (0, 1), or a callable (round, proposal, m, d) -> threshold. The resolved threshold must satisfy d + 1 <= threshold < m. The default is max(d + 1, ceil(Int, 0.3m)). The default covariance regularization is sqrt(eps(T)); an explicit value must be finite and nonnegative. tempering_tolerance must lie strictly between zero and one, tempering_max_iterations and max_backtracking_trials must be positive integers exactly representable as Int, and repulsion_softening must be finite and positive. Real controls are converted to the proposal scalar type T during preparation, with ordinary floating-point rounding allowed.

The target must provide an explicit gradient, a first-order LogDensityProblems interface, or an AD backend through LogTarget. This type adds configuration and fixed prepared state; sampling execution is provided by the method execution layer.

source
ImportanceSamplers.current_rng — Function
current_rng(sampler)

Return an independent snapshot of a prepared sampler's current random stream. Reusing a pure snapshot repeats its stream. Split it explicitly for independent runs.

source

Static MIS schemes

ImportanceSamplers.StratifiedMixture — Type
StratifiedMixture()

Fix stratified proposal assignments from the nominal bank masses before drawing samples, and divide every target value by the full nominal proposal mixture. The aggregate mixture must cover the target support. This is the default scheme for a ProposalBank.

source
ImportanceSamplers.RandomMixture — Type
RandomMixture()

Assign every sample independently from the nominal bank masses, and divide by the full nominal proposal mixture. The aggregate mixture must cover the target support. Compared with StratifiedMixture, this retains iid mixture selection but usually has more assignment-count variation.

source
ImportanceSamplers.StandardMIS — Type
StandardMIS()

Use stratified proposal assignment and divide each target value only by the sample's generating proposal density. Every positive-mass proposal must cover the target support. This costs one proposal-density evaluation per sample but normally gives higher variance than a valid full-mixture denominator.

source
ImportanceSamplers.PartialDeterministicMixture — Type
PartialDeterministicMixture(groups)

Use stratified assignment and divide by the nominal mixture within the sample's generating group. groups must partition all stable proposal IDs exactly once; groups containing only zero-mass proposals are accepted as inert. Each active group mixture must cover the target support.

This interpolates between StandardMIS (singleton groups) and the full mixture denominator (one group), with proposal-density cost proportional to the generating group size.

source

Population resampling

LAIS transitions and tuning

ImportanceSamplers.AbstractMCMCTransition — Type
AbstractMCMCTransition

Abstract supertype for batched MCMC transitions used by LAIS. Built-in transitions are RandomWalkMetropolis, RAM, SampleMetropolisHastings, and HamiltonianMonteCarlo. Custom transitions require the following methods, qualified with ImportanceSamplers except for Base.copyto!.

MethodRequired behavior
prepare_transition(config, centres, target, L)Build state without RNG use and retain the supplied centre storage; L is the log-density type
transition_centres(state)Return the same centre batch without copying
transition!(state, target, rng, execution, transfers)Advance one upper round and update cumulative work counts. Return (next_rng, failure), with nothing for success
Base.copyto!(destination, source)Copy persistent state for rollback
transition_diagnostics(state)Report initial, warmup, and production target evaluations, warmup and production proposals, and accepted moves
retarget_transition(config, state, destination)Rebuild the configuration from learned parameters for retarget

State must support deepcopy. Custom device execution also requires Adapt support, preserved centre aliases, and device preflight. See the transition interface for diagnostic field names and limits. Transitions must return their continued RNG even when target or adaptation work fails after a completed draw; the caller retains it before throwing failure.

source
ImportanceSamplers.RandomWalkMetropolis — Type
RandomWalkMetropolis(covariance)

Configure independent Gaussian random-walk Metropolis chains. covariance is an isotropic variance, an SPD matrix, a Cholesky factorization, or a vector of these inputs with one entry per chain. Use Diagonal for a diagonal covariance. This covariance is independent of the lower importance proposals.

source
ImportanceSamplers.HamiltonianMonteCarlo — Type
HamiltonianMonteCarlo(; step_size, leapfrog_steps, mass=I,
    tuning=WarmupTuning(0), target_acceptance=0.8, divergence_threshold=1000)

Native fixed-length, Metropolis-corrected HMC for vector proposal centres. step_size is the positive integration step and leapfrog_steps is the number of steps per trajectory. mass is the shared momentum covariance, not a lower proposal covariance; use a positive scalar, scaled identity, Diagonal, SPD matrix, or successful Cholesky factorization. No inverse is formed.

WarmupTuning(W) performs W upper-only sweeps and tunes one shared step size by dual averaging, then freezes it across reuse. Mass and trajectory length remain fixed. Scores use the existing LogTarget derivative interface in sampled coordinates, including any configured transform. Scalar-layout banks are not supported; a one-dimensional problem uses a one-element vector.

Finite energy errors above divergence_threshold (in log-density units) are diagnostic only. Numerical integration failures and outside-support candidates reject the trajectory. Invalid initial states, malformed scores and callback failures fail the call without committing partial sampler state.

source
ImportanceSamplers.RAM — Type
RAM(covariance; tuning, target_acceptance=0.234, decay=0.6)

Robust adaptive Metropolis with Gaussian increments and rank-one covariance updates. Covariance inputs follow RandomWalkMetropolis. Choose WarmupTuning or ContinuousTuning explicitly. Adaptation uses the acceptance probability, including on rejected moves, with gain k^(-decay). Lower importance-proposal covariances stay fixed.

source
ImportanceSamplers.SampleMetropolisHastings — Type
SampleMetropolisHastings(proposal; moves=1)

Configure an interacting Sample Metropolis-Hastings transition for a population of LAIS centres. proposal is a fixed independent native Gaussian or Student-t proposal. Each move draws one candidate, selects one old centre with probability proportional to proposal(x) / target(x), and applies the population acceptance probability S / (S + r_candidate - min(r_candidate, r_1, ..., r_N)), where r_i = proposal(x_i) / target(x_i) and S = sum(r_i) over the old population. Set moves explicitly to perform an ordered sweep before each lower LAIS round. One move is the I²-MAIS paper default; moves=N means N ordered replacement attempts, not one guaranteed update of every centre.

The upper proposal and centre bank must have the same scalar/vector layout, dimension, and Float32 or Float64 precision. Initial centres require finite target and proposal log densities. Candidates outside target support are rejected. Successful calls retain centres and cached ratios; retargeting starts a fresh target cache, and failed LAIS calls preserve the pre-call committed state without restoring the RNG.

source

Factor execution

ImportanceSamplers.BatchedFactorExecution — Type
BatchedFactorExecution()

Use matrix multiplication and triangular solves for FactorGaussian and FactorStudentT draws and densities. Student-t draws share one radial multiplier across each sample's coordinates.

Sampling pathBatched factors
Plain IS with no transform or IdentityTransformGaussian and Student-t
Static MIS with a full-mixture denominatorPacked Gaussian and Student-t banks
Adaptive samplingSupported packed factor banks and proposal histories
Other proposals, transforms, or unsupported devicesFusedFactorExecution fallback

CPU uses fused execution by default. Supported accelerator paths use batching. Student-t batching needs one extra dimension-by-count workspace on the device. Benchmark an explicit override on the target device. See prepare_sampler.

source