diff --git a/Project.toml b/Project.toml index cf446a49..9d38e455 100644 --- a/Project.toml +++ b/Project.toml @@ -3,7 +3,7 @@ uuid = "80f14c24-f653-4e6a-9b94-39d6b0f70001" keywords = ["markov chain monte carlo", "probabilistic programming"] license = "MIT" desc = "A lightweight interface for common MCMC methods." -version = "5.16.0" +version = "5.17.0" [deps] BangBang = "198e06fe-97b7-11e9-32a5-e1d131e6ad66" diff --git a/docs/src/api.md b/docs/src/api.md index 48f9fa9a..c210c709 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -135,6 +135,7 @@ AbstractMCMC defines the abstract type `AbstractChains` for Markov chains. ```@docs AbstractMCMC.AbstractChains +AbstractMCMC.SamplingOutput ``` The following two functions exist for converting `AbstractChains` from and to matrices of samples. diff --git a/history.md b/history.md new file mode 100644 index 00000000..a84a8b20 --- /dev/null +++ b/history.md @@ -0,0 +1,5 @@ +# History + +## 5.17.0 + +- Add `SamplingOutput` to retain draws, iteration indices, timing, and optional sampler states in a common container that chain packages can convert to their own formats ([#218](https://github.com/TuringLang/AbstractMCMC.jl/pull/218)). diff --git a/src/AbstractMCMC.jl b/src/AbstractMCMC.jl index 1257e883..40ddbc0e 100644 --- a/src/AbstractMCMC.jl +++ b/src/AbstractMCMC.jl @@ -15,7 +15,7 @@ using UUIDs: UUIDs # Reexport sample using StatsBase: sample -export sample +export sample, SamplingOutput # Parallel sampling types export MCMCThreads, MCMCDistributed, MCMCSerial @@ -193,6 +193,7 @@ end include("samplingstats.jl") include("logging.jl") include("interface.jl") +include("chains.jl") include("sample.jl") include("stepper.jl") include("logdensityproblems.jl") diff --git a/src/chains.jl b/src/chains.jl new file mode 100644 index 00000000..1334b17e --- /dev/null +++ b/src/chains.jl @@ -0,0 +1,109 @@ +""" + SamplingOutput(samples; iterations=1:size(samples, 1), sampling_stats, sampler_states) + +Store a matrix of samples and their chain-level metadata. + +Rows are iterations and columns are chains. Each entry holds a draw, including any +recorded sampler statistics. The entry type is parametric: for example, a sampler can use +a `NamedTuple` or its own type for parameters and statistics. `iterations` records the +iteration indices before thinning. +`sampling_stats` contains one `SamplingStats` or `missing` per chain, and `sampler_states` +contains one saved state or `missing` per chain. Both default to `missing`; sampler states +are retained only when sampling with `save_state=true`. +Specialize `Base.show(io::IO, ::MIME"text/plain", ::SamplingOutput{<:MyDraw})` for custom display. +""" +struct SamplingOutput{T,I<:AbstractRange{<:Integer},S<:Union{SamplingStats,Missing},L} <: + AbstractChains + samples::Matrix{T} + iterations::I + sampling_stats::Vector{S} + sampler_states::Vector{L} + + function SamplingOutput( + samples::Matrix{T}; + iterations::I=1:size(samples, 1), + sampling_stats::Vector{S}=fill(missing, size(samples, 2)), + sampler_states::Vector{L}=fill(missing, size(samples, 2)), + ) where {T,I<:AbstractRange{<:Integer},S<:Union{SamplingStats,Missing},L} + length(iterations) == size(samples, 1) || + throw(DimensionMismatch("one iteration index is required per sample row")) + Base.step(iterations) > 0 || throw(ArgumentError("iteration indices must increase")) + length(sampling_stats) == length(sampler_states) == size(samples, 2) || throw( + DimensionMismatch( + "one sampling-statistics and sampler-state entry is required per chain" + ), + ) + return new{T,I,S,L}(samples, iterations, sampling_stats, sampler_states) + end +end + +Base.size(chain::SamplingOutput, args...) = size(chain.samples, args...) +Base.getindex(chain::SamplingOutput, args...) = getindex(chain.samples, args...) +Base.firstindex(chain::SamplingOutput, args...) = firstindex(chain.samples, args...) +Base.lastindex(chain::SamplingOutput, args...) = lastindex(chain.samples, args...) + +function Base.show(io::IO, ::MIME"text/plain", output::SamplingOutput) + n, m = size(output) + times = [round(s.duration; sigdigits=3) for s in skipmissing(output.sampling_stats)] + timing = isempty(times) ? missing : (min=minimum(times), max=maximum(times)) + chains = m == 1 ? "chain" : "chains" + println(io, "SamplingOutput: $m $chains, $n draws each") + discard_initial = first(output.iterations) - 1 + thinning = Base.step(output.iterations) + println(io, " Total draws: $(n * m) ", (; discard_initial, thinning)) + println(io, " Time/chain (s): ", timing) + println(io) + return printstyled( + io, + "For MCMC diagnostics and plotting, use FlexiChains, MCMCChains, or ArviZ."; + color=:light_black, + ) +end + +function _bundle_samples( + samples::AbstractVecOrMat, + ::AbstractModel, + ::AbstractSampler, + state, + ::Type{C}; + save_state=false, + stats=missing, + discard_initial=0, + thinning=1, + kwargs..., +) where {C<:SamplingOutput} + samples = samples isa Array ? samples : collect(samples) + samples = samples isa Vector ? reshape(samples, :, 1) : samples + return from_samples( + C, + samples; + iterations=range(discard_initial + 1; step=thinning, length=size(samples, 1)), + sampling_stats=fill(stats, size(samples, 2)), + sampler_states=fill(save_state ? state : missing, size(samples, 2)), + ) +end + +chainsstack(chains::AbstractVector{<:SamplingOutput}) = chainscat(chains...) + +function chainscat(chain::SamplingOutput, chains::SamplingOutput...) + all(c -> c.iterations == chain.iterations, chains) || + throw(ArgumentError("chains must have matching iteration indices")) + all_chains = (chain, chains...) + return SamplingOutput( + hcat(map(c -> c.samples, all_chains)...); + iterations=chain.iterations, + sampling_stats=vcat(map(c -> c.sampling_stats, all_chains)...), + sampler_states=vcat(map(c -> c.sampler_states, all_chains)...), + ) +end + +function to_samples(::Type{T}, chain::SamplingOutput) where {T} + return convert(Matrix{T}, chain.samples) +end + +from_samples(::Type{SamplingOutput}, s::Matrix; kw...) = SamplingOutput(s; kw...) +function from_samples(::Type{C}, samples::Matrix; kw...) where {T,C<:SamplingOutput{T}} + chain = SamplingOutput(convert(Matrix{T}, samples); kw...) + chain isa C || throw(ArgumentError("samples and metadata cannot construct $C")) + return chain +end diff --git a/src/interface.jl b/src/interface.jl index d4d935a9..ad37a074 100644 --- a/src/interface.jl +++ b/src/interface.jl @@ -27,7 +27,12 @@ Bundle all `samples` that were sampled from the `model` with the given `sampler` The final `state` of the `sampler` can be included in the chain. The type of the chain can be specified with the `chain_type` argument. -By default, this method returns `samples`. +For a [`SamplingOutput`](@ref) output type, the default `_bundle_samples` collects a vector +or matrix of samples and its metadata in that representation. Chain packages can implement +`Base.convert(::Type{MyChains}, output::SamplingOutput)` for explicit conversion after +sampling with `chain_type=SamplingOutput`, or overload `bundle_samples` to construct their +chain objects directly from raw samples. +Otherwise, this method returns `samples` (or converts its entries for `Vector{T}` output). """ function bundle_samples( samples, model::AbstractModel, sampler::AbstractSampler, state, ::Type{T}; kwargs... diff --git a/test/chains.jl b/test/chains.jl new file mode 100644 index 00000000..04f5a5b8 --- /dev/null +++ b/test/chains.jl @@ -0,0 +1,89 @@ +module SamplingOutputTests +using AbstractMCMC, Random, Test +using AbstractMCMC: bundle_samples, chainscat, chainsstack, from_samples, to_samples + +struct Model <: AbstractMCMC.AbstractModel end +struct Sampler <: AbstractMCMC.AbstractSampler end +function AbstractMCMC.step(rng, ::Model, ::Sampler, state=0; kwargs...) + return (x=rand(rng), iteration=state + 1), state + 1 +end + +struct ConvertedChain{C<:SamplingOutput} <: AbstractMCMC.AbstractChains + chain::C +end +Base.convert(::Type{ConvertedChain}, chain::SamplingOutput) = ConvertedChain(chain) + +@testset "SamplingOutput" begin + opts = (; discard_initial=2, thinning=3, save_state=true, progress=false) + samples = reshape([(x=1,), (x=2,)], :, 1) + chain = SamplingOutput(samples) + @test chain[2, 1] == (x=2,) + @test to_samples(eltype(samples), chain) === samples + @test to_samples(NamedTuple, chain) isa Matrix{NamedTuple} + @test to_samples(NamedTuple, chain) == samples + @test to_samples(Float64, SamplingOutput(ones(Int, 1, 1))) isa Matrix{Float64} + @test from_samples(SamplingOutput, samples).samples === samples + @test from_samples(typeof(chain), to_samples(NamedTuple, chain)) isa typeof(chain) + @test from_samples(typeof(chain), samples).samples === samples + @test from_samples(SamplingOutput{Float64}, ones(Int, 1, 1)) isa SamplingOutput{Float64} + many = [SamplingOutput(fill(i, 128, 1)) for i in 1:64] + @test chainsstack(many).samples == repeat(reshape(1:64, 1, :), 128) + @test (@allocated chainsstack(many)) < 4 * 128 * 64 * sizeof(Int) + matrix = [(x=i, walker=j) for i in 1:3, j in 1:2] + indexed = SamplingOutput(matrix) + @test indexed[begin] == matrix[begin] + @test indexed[end] == matrix[end] + @test indexed[begin, end] == matrix[begin, end] + @test indexed[end, begin] == matrix[end, begin] + @test indexed[begin:end, begin:end] == matrix + @test convert(SamplingOutput, chain) === chain + @test convert(typeof(chain), chain) === chain + @test all(ismissing, chain.sampling_stats) + @test all(ismissing, chain.sampler_states) + plain = sprint(show, MIME"text/plain"(), chain) + @test startswith(plain, "SamplingOutput: 1 chain, 2 draws each\n Total draws:") + @test occursin("use FlexiChains, MCMCChains, or ArviZ.", plain) + @test occursin("Total draws: 2 (discard_initial = 0, thinning = 1)", plain) + @test !occursin('\e', plain) + @test occursin('\e', sprint(show, MIME"text/plain"(), chain; context=:color => true)) + @test_throws DimensionMismatch SamplingOutput(samples; iterations=1:3) + @test_throws ArgumentError SamplingOutput(samples; iterations=2:-1:1) + @test_throws DimensionMismatch SamplingOutput( + samples; sampling_stats=[missing, missing] + ) + @test_throws DimensionMismatch SamplingOutput(samples; sampler_states=[]) + @test_throws ArgumentError chainscat(chain, SamplingOutput(samples; iterations=2:3)) + converted = sample( + Xoshiro(1), Model(), Sampler(), 3; chain_type=SamplingOutput{NamedTuple}, opts... + ) + converted = convert(ConvertedChain, converted).chain + @test converted isa SamplingOutput{NamedTuple} + @test converted.iterations == 3:3:9 + @test converted.sampler_states == [9] + @test only(converted.sampling_stats).duration >= 0 + @test_throws ArgumentError from_samples(typeof(converted), converted.samples) + for chain_type in (Any, Vector{NamedTuple}, ConvertedChain, AbstractMCMC.AbstractChains) + raw = sample(Xoshiro(1), Model(), Sampler(), 3; chain_type, progress=false) + @test raw isa Vector{<:NamedTuple} + end + for draws in (matrix, view(matrix, :, :)) + chain = bundle_samples(draws, Model(), Sampler(), 9, SamplingOutput; opts...) + @test chain.samples == matrix + @test chain.iterations == 3:3:9 + @test chain.sampler_states == [9, 9] + @test all(ismissing, chain.sampling_stats) + draws === matrix && @test chain.samples === matrix + end + @testset "sampling: $ensemble" for ensemble in (nothing, MCMCSerial(), MCMCThreads()) + args = ensemble === nothing ? (3,) : (ensemble, 3, 2) + chain = sample( + Xoshiro(1), Model(), Sampler(), args...; chain_type=SamplingOutput, opts... + ) + @test size(chain) == (3, ensemble === nothing ? 1 : 2) + @test chain.iterations == 3:3:9 + @test all(==(9), chain.sampler_states) + @test all(s -> s.duration >= 0, chain.sampling_stats) + @test all(c -> getproperty.(c, :iteration) == 3:3:9, eachcol(chain.samples)) + end +end +end diff --git a/test/runtests.jl b/test/runtests.jl index c168b157..4750d391 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -25,6 +25,7 @@ include("utils.jl") @testset "AbstractMCMC" begin include("sample.jl") + include("chains.jl") include("stepper.jl") include("logdensityproblems.jl") end