Batch targets

A scalar target evaluates one draw. An optional batch callback evaluates many draws with shared matrix operations or device kernels.

Batched linear regression

using ImportanceSamplers, PureRNGs, Random, Statistics, LinearAlgebrafunction logtarget(beta, p)    value = -sum(abs2, beta) / 8    for row in axes(p.X, 1)        residual = -p.y[row]        for column in eachindex(beta)            residual += p.X[row, column] * beta[column]        end        value -= residual^2 / 2    end    return valueendfunction batch!(values, samples, p)    residuals = p.X * samples .- p.y    values .= .-vec(sum(abs2, residuals; dims=1)) ./ 2 .-              vec(sum(abs2, samples; dims=1)) ./ 8    return nothingendrng = Xoshiro(42)X = randn(rng, 80, 3)y = X * [-0.4, 1.1, -0.8] + randn(rng, 80)p = (; X, y)proposal = SphericalGaussian(X \ y, 0.3)target = LogTarget(logtarget; batch=batch!)samples = importance_sample(    Threefry4x32(43), target, p,    ImportanceSampling(proposal; nsamples=5_000),)mean(samples)
3-element Vector{Float64}:
 -0.4272852685593874
  1.1854496295209156
 -0.7351633135465296

The model has unit observation noise and independent Normal(0, 2) coefficient priors. The scalar and batch functions compute the same unnormalized log posterior.

Each sample is a column. The matrix multiplication p.X * samples evaluates all proposed coefficient vectors together.

Callback interface

Scalar target inputBatch inputOutput buffer
ScalarLength-n vectorLength-n vector
Length-d vectord × n matrixLength-n vector
Named parametersNamed tuple of batched leavesLength-n vector

With no context, use batch!(values, samples). With context, use batch!(values, samples, p). The scalar callable remains required.

Fill every output entry. Accept array views rather than requiring concrete Matrix types. Treat inputs as read-only and retain none of the borrowed buffers. The return value is ignored.

Each output must equal the scalar target for that sample. It must not depend on other samples or the batch width. Widths may vary. Empty batches are skipped.

Sample order and derived outputs

values[j] must describe input sample j: column j for a vector parameter, or index j along the final axis of each named leaf. The callback must not reorder the inputs.

For ImportanceSampling, callback samples have the same order as result.samples, including when the proposal is a ProposalBank. Per-column derived quantities computed alongside the log density, such as power-flow outputs, can therefore be associated with the same result columns. Copy any inputs or derived outputs you need after the callback returns; do not save references to the borrowed buffers.

Adaptive methods preserve the order within each retained sampling batch. AMIS concatenates its newly drawn batches in chronological round order, including unequal round sizes. It caches earlier target values; retrospective reweighting does not reorder the samples or reevaluate those targets.

Not every target call produces a retained sample. Upper MCMC moves, gradient evaluations, backtracking trials, and padded candidates can evaluate other points. Do not concatenate all callback outputs for methods with such auxiliary calls; compute derived quantities from the final result.samples when the retained calls cannot be identified separately. With named transforms, both the batch callback and result.samples contain logical values, not unconstrained coordinates.

Parallelism and memory

The callback controls CPU parallelism. threaded=true does not divide one callback into concurrent calls. Proposal and weighting work retain their normal execution policy.

The example allocates an observations-by-samples residual matrix. For large datasets, use bounded internal blocks or reusable model-specific scratch where appropriate. Scratch must remain valid for the callback's actual width and device.

Without batch=, the package already evaluates independent scalar targets in parallel. A batch callback changes how the model computes, not whether the sampler can run in parallel.

Transforms, gradients, and devices

With transform=, the callback receives logical named leaves. The package adds the Jacobian. Do not add it in the callback.

grad= and AD selectors remain independent of batch=. Automatic differentiation uses the scalar target, not this callback. Use batch_grad= for combined batched values and gradients. It remains separate so value-only phases do not compute unnecessary gradients.

A device callback receives resident inputs, outputs, and context. Use the current task's stream or complete private-stream work before returning. Failure checks may synchronize at batch boundaries, not once per sample.

Adaptive execution

Adaptive methods batch the current round's samples. AMIS caches earlier target values.

LAIS cannot combine dependent future MCMC steps into one target evaluation. GRAMIS similarly cannot evaluate future backtracking trials in advance.

Native GRAMIS batches only active backtracking candidates. Reactant uses fixed-width padded batches so prepared executables can be reused. Inactive candidates retain their accepted locations and their new values are discarded. Their extra evaluations appear in the diagnostics.

Scalar and batch performance

Batching can help data-heavy matrix models. Cheap scalar targets can be faster with fused scalar execution. Measure both on the intended model and device.

The standalone example also shows CUDA transfer. The benchmark guide links paired scalar/batch measurements.