Results and statistics

See Weighted samples for weighted estimates, indexing, and device rules. See Pareto smoothing for a raw-IS comparison and tail diagnostics.

Containers and weights

ImportanceSamplers.WeightedSamples — Type
WeightedSamples(samples, logweights; provenance=NamedTuple(), diagnostics=NamedTuple(),
                logtargets=nothing, retained=nothing)

Construct a complete weighted-sample result with independent copies of the input arrays.

samples is a numeric vector, numeric matrix, or nonempty named-tuple tree of those arrays. Its final logical axis must align with the raw, unnormalized logweights. Plain importance sampling normally constructs this type through importance_sample or importance_sample!.

Scalar indexing and iteration return aligned named tuples with sample, logweight, and provenance fields. Range, integer-vector, and Boolean-mask indexing return a WeightedSampleView.

logtargets is nothing unless target values were retained, or an aligned vector on the same device. Samplers retain these values with save_logtargets=true. They are exact log densities in sampling coordinates, including the forward Jacobian for transform=, not necessarily densities of the returned logical samples. Views retain aligned target values without adding them to iteration records.

retained is nothing unless a RetainCoordinates target saved mapped parameters and Jacobians. Views and device copies preserve their alignment.

Apply an MLDataDevices.AbstractDevice to a complete result to create an independent copy on that device. Device-resident results must be transferred to CPU before scalar indexing, iteration, quantiles, or medians.

source
ImportanceSamplers.WeightedSampleView — Type
WeightedSampleView

An aligned descriptive view of a subset of weighted samples.

Views support indexing, iteration, and normalized_weights, but not lognormalizer, because an arbitrary subset is not a complete estimator result. Construct views by indexing a WeightedSamples. Device-resident views retain device storage. Apply an MLDataDevices.AbstractDevice directly to create an independent aligned copy; transfer to CPU before scalar indexing or iteration.

source
ImportanceSamplers.ParetoSmoothedSamples — Type
ParetoSmoothedSamples

A weighted-sample result returned by psis. Samples, saved log targets, and provenance are shared with the input and must remain read-only. logweights contains a separate array of unnormalized Pareto-smoothed log weights. Existing weighted statistics, indexing, and resampling use these weights.

diagnostics reports pareto_k, tail_length, threshold, relative_efficiency, status, reliable, and transfer counts for PSIS and later result operations, not the generation of the input. reliable concerns the fitted weight tail, not support coverage, arbitrary functionals, or adaptive dependence. lognormalizer is deliberately unavailable: smoothing changes that estimator. Keep the original result for its raw normalizer.

source
ImportanceSamplers.UnweightedSamples — Type
UnweightedSamples(samples)

Construct a batch of unweighted samples by copying the input arrays. Logical samples occupy the final array axis and support scalar indexing and iteration on CPU storage.

source
ImportanceSamplers.normalized_weights — Function
normalized_weights(result)

Derive an array of weights that sums to one from a complete result or descriptive view.

The raw result.logweights remain unchanged. If every raw log weight is -Inf, throw AllZeroWeightsError rather than inventing uniform weights. For a device-resident result, the returned weight array stays on the same device. Float16 log weights use Float32 accumulation and normalized output.

source
ImportanceSamplers.lognormalizer — Function
lognormalizer(result::WeightedSamples)

Return logsumexp(result.logweights) - log(length(result)), the log of the plain-importance-sampling normalizer estimate.

This is Bayesian log evidence only if the supplied target retains every required normalizing constant. It returns -Inf when all raw weights are zero. It is unavailable on WeightedSampleView, which is not a complete estimator. Device-resident complete results use a device reduction and transfer only its two-scalar log-sum-exp accumulator.

source
ImportanceSamplers.psis — Function
psis(result; reff=1, threaded=true)
psis(logweights::AbstractVector; reff=1, threaded=true)

Apply Pareto-smoothed importance sampling to final, unnormalized log weights. The input remains unchanged. A sample result gives ParetoSmoothedSamples, sharing its samples and provenance. A log-weight vector gives (; logweights, diagnostics).

Fit the largest floor(min(n/5, 3sqrt(n/reff))) ratios using Zhang–Stephens estimation and shape regularization, replace them by fitted Pareto quantiles, and cap them at the largest raw ratio. This follows Algorithm 1 and Appendices F–H of Vehtari et al. (2024).

reff is a supplied relative MCMC efficiency in (0, 1], not weight ESS divided by n. The default describes independent draws. It does not correct arbitrary adaptive dependence. The diagnostic threshold is min(1 - 1/log10(n), 0.7). A large pareto_k flags unstable estimates, not proof that the target is improper.

status == :smoothed means a tail fit succeeded. Too-short or degenerate tails and numerical fit failures retain the raw weights, with an unavailable (NaN) pareto_k and reliable=false. Tied tail values receive their block's mean smoothed mass, so their order cannot change an estimate. A tie across the cutoff, or a selected zero ratio, retains all raw weights with status=:degenerate_tail. These conservative tie rules extend the paper's continuous-ratio algorithm. All-zero weights throw AllZeroWeightsError. NaN and positive-infinite log weights are invalid.

Arrays retain their device and precision. Only scalar diagnostics reach the host. threaded=false disables CPU worker tasks, not GPU execution. GPU execution needs device sorting and floating-point support from the selected backend. Smoothing does not discover missed modes, repair support, or change any sampler's adaptation.

source

Statistics

Statistics.mean — Function
Statistics.mean(result)

Return the self-normalized weighted mean of the sampled parameters.

source
Statistics.mean(f, result)

Return the self-normalized weighted expectation of the scalar function f. Evaluate one value per sample without transferring a device-resident result to CPU.

source
Statistics.mean(samples::UnweightedSamples)
Statistics.mean(f, samples::UnweightedSamples)

Return an ordinary unweighted expectation over logical samples.

source
Statistics.var — Function
Statistics.var(result; corrected=false)

Return the uncorrected weighted target variance. corrected=true is unsupported because importance weights have no general sample-variance correction.

source
Statistics.var(f, result; corrected=false)

Return the weighted target variance of the scalar function f. As with var(result), corrected=true is unsupported.

source
Statistics.var(samples::UnweightedSamples; corrected=true)
Statistics.var(f, samples::UnweightedSamples; corrected=true)

Return the ordinary unweighted sample variance.

source
Statistics.std — Function
Statistics.std(result; corrected=false)

Return the square root of the corresponding weighted target variance.

source
Statistics.std(f, result; corrected=false)

Return the square root of var(f, result; corrected).

source
Statistics.cov — Function
Statistics.cov(result; corrected=false)

Return the uncorrected weighted covariance matrix for vector-valued samples. corrected=true is unsupported.

source
Statistics.quantile — Function
Statistics.quantile(result, probability)
Statistics.quantile(result, probabilities)

Return component-wise weighted quantiles using the StatsBase generic-weight interpolation rule. Transfer device-resident results to CPU before calling.

source

Control variates

ImportanceSamplers.fit_control_variate — Function
fit_control_variate(f, pilot; scores, ridge=1e-6, threaded=true)

Fit a SteinControlVariate for a scalar expectation. Supply a callable f(x) or an aligned cached vector. The pilot must contain nonempty flat Float32/Float64 vectors. scores[:,i] is the exact physical-coordinate target score ∇logtarget(x_i), with matching shape, precision, and device.

The controls are scores[j,i] and 1 + (x[j,i]-center[j])*scores[j,i]. Their target expectations must be zero: the target must be differentiable and the corresponding boundary flux must vanish. These conditions are not inferred from samples. Hard constraints require valid unconstrained coordinates or boundary-compatible controls. No Hessian or derivative of f is needed.

Fit w*(f-mean(f,pilot)) against w*controls, with column scaling and ridge. The squared-weight objective targets fixed-proposal self-normalized IS asymptotic variance when pilot and production use the same proposal. Other pilots give a heuristic fit. Improvement is not guaranteed. ridge=0 requires full-rank pilot controls; singular systems fail without a fallback.

Freeze the fit and use independent production draws. Self-normalization still has finite-sample ratio bias. Inputs remain unchanged, zero-weight rows are ignored, and scalar values use the sample precision. Only the small regression system returns to CPU for a solve. The fit stays on the pilot device. threaded=false disables CPU worker tasks, not accelerator execution. See Score control variates.

source
ImportanceSamplers.control_variate_mean — Function
control_variate_mean(f, samples, fit::SteinControlVariate; scores, threaded=true)

Return sum(normalized_weights(samples) .* (f - controls' * fit.coefficients)). Supply a scalar callable or aligned cached values for the same functional used in fitting. Scores use the same target and coordinates as the fit. Samples, scores, fit arrays, and cached values must share a device. Scores and fit arrays must match the sample precision and dimension.

The fit must be independent of these production draws. Start with independent fixed-proposal production IS. This function does not certify adaptive-history uncertainty, boundary conditions, or proposal support. It does not change the samples, weights, weight ESS, resampling, or normalizer. The result is an expectation estimate, not a weighted sample container or a Monte Carlo error. Scores and sample-sized work stay on-device. Only scalar checks and the final estimate reach the host. See fit_control_variate.

source

Resampling

ImportanceSamplers.resample_next — Function
resample_next(rng, result, count=length(result); method=MultinomialResampling())

Draw with replacement from normalized importance weights using a PureRNGs stream. Return (unweighted_samples, next_rng). Samples stay on the result device. The immutable RNG continues on its input backend. For Reactant results, pass a compiled carrier from current_rng or Reactant.to_rarray(rng). The returned continuation is also a compiled carrier.

source