From 3bbffa72fb46b89ba85d7f093e8b3f1743268dab Mon Sep 17 00:00:00 2001 From: Hong Ge Date: Sat, 12 Sep 2026 13:24:22 +0100 Subject: [PATCH 1/4] chains: add `SamplingOutput` for draws and sampling metadata Assisted-by: Codex --- Project.toml | 2 +- docs/src/api.md | 1 + src/AbstractMCMC.jl | 3 +- src/chains.jl | 99 +++++++++++++++++++++++++++++++++++++++++ src/interface.jl | 5 ++- test/chains.jl | 104 ++++++++++++++++++++++++++++++++++++++++++++ test/runtests.jl | 1 + 7 files changed, 212 insertions(+), 3 deletions(-) create mode 100644 src/chains.jl create mode 100644 test/chains.jl diff --git a/Project.toml b/Project.toml index 37d9aa42..22cdb768 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-DEV" [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/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..7d7cb34c --- /dev/null +++ b/src/chains.jl @@ -0,0 +1,99 @@ +""" + 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`. +""" +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...) + +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<:AbstractChains} + samples = samples isa Array ? samples : collect(samples) + samples = samples isa Vector ? reshape(samples, :, 1) : samples + chain = SamplingOutput( + 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)), + ) + return convert(C, chain) +end + +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{<:T}) where {T} + return chain.samples +end + +from_samples(::Type{SamplingOutput}, samples::Matrix) = SamplingOutput(samples) diff --git a/src/interface.jl b/src/interface.jl index d4d935a9..fb304c99 100644 --- a/src/interface.jl +++ b/src/interface.jl @@ -27,7 +27,10 @@ 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 an `AbstractChains` output type, the default implementation collects a vector or matrix +of samples and its metadata in a [`SamplingOutput`](@ref), then calls `convert(chain_type, chain)`. +Chain packages can implement this conversion instead of overloading `bundle_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..d226e244 --- /dev/null +++ b/test/chains.jl @@ -0,0 +1,104 @@ +module SamplingOutputTests + +using AbstractMCMC +using Random +using Test + +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 + samples = reshape([(x=1,), (x=2,)], :, 1) + chain = SamplingOutput(samples) + @test chain[2, 1] == (x=2,) + @test AbstractMCMC.to_samples(NamedTuple, chain) === samples + @test AbstractMCMC.from_samples(SamplingOutput, samples).samples === samples + @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 AbstractMCMC.chainscat( + chain, SamplingOutput(samples; iterations=2:3) + ) + + converted = + sample( + Xoshiro(1), + Model(), + Sampler(), + 3; + chain_type=ConvertedChain, + discard_initial=2, + thinning=3, + save_state=true, + progress=false, + ).chain + @test converted.iterations == 3:3:9 + @test converted.sampler_states == [9] + @test only(converted.sampling_stats).duration >= 0 + for chain_type in (Any, Vector{NamedTuple}) + raw = sample(Xoshiro(1), Model(), Sampler(), 3; chain_type, progress=false) + @test raw isa Vector{<:NamedTuple} + end + + matrix = [(x=i, walker=j) for i in 1:3, j in 1:2] + for draws in (matrix, view(matrix, :, :)) + chain = AbstractMCMC.bundle_samples( + draws, + Model(), + Sampler(), + 9, + SamplingOutput; + discard_initial=2, + thinning=3, + save_state=true, + ) + @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, + discard_initial=2, + thinning=3, + save_state=true, + progress=false, + ) + @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 1c775d15..5dc225ef 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -21,6 +21,7 @@ include("utils.jl") @testset "AbstractMCMC" begin include("sample.jl") + include("chains.jl") include("stepper.jl") include("logdensityproblems.jl") end From dc16cb7d2ab41006866568efa80f081039fc93d8 Mon Sep 17 00:00:00 2001 From: Hong Ge Date: Sun, 20 Sep 2026 18:37:37 +0100 Subject: [PATCH 2/4] chains: support concrete round trips and index bounds Assisted-by: Codex --- Project.toml | 2 +- src/chains.jl | 14 ++++++++-- src/interface.jl | 8 ++++-- test/chains.jl | 73 +++++++++++++++++++----------------------------- 4 files changed, 47 insertions(+), 50 deletions(-) diff --git a/Project.toml b/Project.toml index 22cdb768..d56f3c39 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.17.0-DEV" +version = "5.17.0" [deps] BangBang = "198e06fe-97b7-11e9-32a5-e1d131e6ad66" diff --git a/src/chains.jl b/src/chains.jl index 7d7cb34c..4dbbce08 100644 --- a/src/chains.jl +++ b/src/chains.jl @@ -10,6 +10,7 @@ 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 @@ -38,6 +39,8 @@ 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) @@ -80,6 +83,8 @@ function _bundle_samples( return convert(C, chain) 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")) @@ -92,8 +97,13 @@ function chainscat(chain::SamplingOutput, chains::SamplingOutput...) ) end -function to_samples(::Type{T}, chain::SamplingOutput{<:T}) where {T} - return chain.samples +function to_samples(::Type{T}, chain::SamplingOutput) where {T} + return convert(Matrix{T}, chain.samples) end from_samples(::Type{SamplingOutput}, samples::Matrix) = SamplingOutput(samples) +function from_samples(::Type{C}, samples::Matrix) where {T,C<:SamplingOutput{T}} + chain = SamplingOutput(convert(Matrix{T}, samples)) + chain isa C || throw(ArgumentError("cannot reconstruct $C from samples alone")) + return chain +end diff --git a/src/interface.jl b/src/interface.jl index fb304c99..b9b5e0c1 100644 --- a/src/interface.jl +++ b/src/interface.jl @@ -27,9 +27,11 @@ 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. -For an `AbstractChains` output type, the default implementation collects a vector or matrix -of samples and its metadata in a [`SamplingOutput`](@ref), then calls `convert(chain_type, chain)`. -Chain packages can implement this conversion instead of overloading `bundle_samples`. +For an `AbstractChains` output type, the default `_bundle_samples` collects a vector or matrix +of samples and its metadata in a [`SamplingOutput`](@ref), AbstractMCMC's internal chain +representation, then calls `convert(chain_type, chain)`. Chain packages can implement +`Base.convert(::Type{MyChains}, output::SamplingOutput)` and use this default without +overloading `bundle_samples` or its internal helper `_bundle_samples`. Otherwise, this method returns `samples` (or converts its entries for `Vector{T}` output). """ function bundle_samples( diff --git a/test/chains.jl b/test/chains.jl index d226e244..52754ce0 100644 --- a/test/chains.jl +++ b/test/chains.jl @@ -1,8 +1,6 @@ module SamplingOutputTests - -using AbstractMCMC -using Random -using Test +using AbstractMCMC, Random, Test +using AbstractMCMC: bundle_samples, chainscat, chainsstack, from_samples, to_samples struct Model <: AbstractMCMC.AbstractModel end struct Sampler <: AbstractMCMC.AbstractSampler end @@ -16,11 +14,28 @@ 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 AbstractMCMC.to_samples(NamedTuple, chain) === samples - @test AbstractMCMC.from_samples(SamplingOutput, samples).samples === samples + @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) @@ -37,61 +52,32 @@ Base.convert(::Type{ConvertedChain}, chain::SamplingOutput) = ConvertedChain(cha samples; sampling_stats=[missing, missing] ) @test_throws DimensionMismatch SamplingOutput(samples; sampler_states=[]) - @test_throws ArgumentError AbstractMCMC.chainscat( - chain, SamplingOutput(samples; iterations=2:3) - ) + @test_throws ArgumentError chainscat(chain, SamplingOutput(samples; iterations=2:3)) - converted = - sample( - Xoshiro(1), - Model(), - Sampler(), - 3; - chain_type=ConvertedChain, - discard_initial=2, - thinning=3, - save_state=true, - progress=false, - ).chain + converted = sample( + Xoshiro(1), Model(), Sampler(), 3; chain_type=ConvertedChain, opts... + ) + converted = converted.chain @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}) raw = sample(Xoshiro(1), Model(), Sampler(), 3; chain_type, progress=false) @test raw isa Vector{<:NamedTuple} end - - matrix = [(x=i, walker=j) for i in 1:3, j in 1:2] for draws in (matrix, view(matrix, :, :)) - chain = AbstractMCMC.bundle_samples( - draws, - Model(), - Sampler(), - 9, - SamplingOutput; - discard_initial=2, - thinning=3, - save_state=true, - ) + 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, - discard_initial=2, - thinning=3, - save_state=true, - progress=false, + Xoshiro(1), Model(), Sampler(), args...; chain_type=SamplingOutput, opts... ) @test size(chain) == (3, ensemble === nothing ? 1 : 2) @test chain.iterations == 3:3:9 @@ -100,5 +86,4 @@ Base.convert(::Type{ConvertedChain}, chain::SamplingOutput) = ConvertedChain(cha @test all(c -> getproperty.(c, :iteration) == 3:3:9, eachcol(chain.samples)) end end - end From b482dd028612de6187dc0d06e25da98e9deaedef Mon Sep 17 00:00:00 2001 From: Hong Ge Date: Sun, 20 Sep 2026 19:30:22 +0100 Subject: [PATCH 3/4] chains: make sampling output bundling opt-in Preserve the raw-sample fallback for other chain types. Conversion from `SamplingOutput` remains available explicitly after sampling. Assisted-by: Codex --- history.md | 5 +++++ src/chains.jl | 2 +- src/interface.jl | 10 +++++----- test/chains.jl | 6 +++--- 4 files changed, 14 insertions(+), 9 deletions(-) create mode 100644 history.md 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/chains.jl b/src/chains.jl index 4dbbce08..e336f3ba 100644 --- a/src/chains.jl +++ b/src/chains.jl @@ -71,7 +71,7 @@ function _bundle_samples( discard_initial=0, thinning=1, kwargs..., -) where {C<:AbstractChains} +) where {C<:SamplingOutput} samples = samples isa Array ? samples : collect(samples) samples = samples isa Vector ? reshape(samples, :, 1) : samples chain = SamplingOutput( diff --git a/src/interface.jl b/src/interface.jl index b9b5e0c1..7bbce0e0 100644 --- a/src/interface.jl +++ b/src/interface.jl @@ -27,11 +27,11 @@ 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. -For an `AbstractChains` output type, the default `_bundle_samples` collects a vector or matrix -of samples and its metadata in a [`SamplingOutput`](@ref), AbstractMCMC's internal chain -representation, then calls `convert(chain_type, chain)`. Chain packages can implement -`Base.convert(::Type{MyChains}, output::SamplingOutput)` and use this default without -overloading `bundle_samples` or its internal helper `_bundle_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`. Other chain types retain their existing bundling +behavior; defining `convert` alone does not opt them into this helper. Otherwise, this method returns `samples` (or converts its entries for `Vector{T}` output). """ function bundle_samples( diff --git a/test/chains.jl b/test/chains.jl index 52754ce0..d1179b1a 100644 --- a/test/chains.jl +++ b/test/chains.jl @@ -55,14 +55,14 @@ Base.convert(::Type{ConvertedChain}, chain::SamplingOutput) = ConvertedChain(cha @test_throws ArgumentError chainscat(chain, SamplingOutput(samples; iterations=2:3)) converted = sample( - Xoshiro(1), Model(), Sampler(), 3; chain_type=ConvertedChain, opts... + Xoshiro(1), Model(), Sampler(), 3; chain_type=SamplingOutput, opts... ) - converted = converted.chain + converted = convert(ConvertedChain, converted).chain @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}) + 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 From ce4816898255e8efb0aa92b2bb2bb83afbf3f1b7 Mon Sep 17 00:00:00 2001 From: Hong Ge Date: Sun, 20 Sep 2026 19:36:30 +0100 Subject: [PATCH 4/4] chains: honor requested draw types when bundling Reuse sample conversion while retaining sampling metadata. Document explicit conversion and direct bundling as chain construction options. Assisted-by: Codex --- src/chains.jl | 12 ++++++------ src/interface.jl | 4 ++-- test/chains.jl | 4 ++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/chains.jl b/src/chains.jl index e336f3ba..1334b17e 100644 --- a/src/chains.jl +++ b/src/chains.jl @@ -74,13 +74,13 @@ function _bundle_samples( ) where {C<:SamplingOutput} samples = samples isa Array ? samples : collect(samples) samples = samples isa Vector ? reshape(samples, :, 1) : samples - chain = SamplingOutput( + 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)), ) - return convert(C, chain) end chainsstack(chains::AbstractVector{<:SamplingOutput}) = chainscat(chains...) @@ -101,9 +101,9 @@ function to_samples(::Type{T}, chain::SamplingOutput) where {T} return convert(Matrix{T}, chain.samples) end -from_samples(::Type{SamplingOutput}, samples::Matrix) = SamplingOutput(samples) -function from_samples(::Type{C}, samples::Matrix) where {T,C<:SamplingOutput{T}} - chain = SamplingOutput(convert(Matrix{T}, samples)) - chain isa C || throw(ArgumentError("cannot reconstruct $C from samples alone")) +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 7bbce0e0..ad37a074 100644 --- a/src/interface.jl +++ b/src/interface.jl @@ -30,8 +30,8 @@ be specified with the `chain_type` argument. 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`. Other chain types retain their existing bundling -behavior; defining `convert` alone does not opt them into this helper. +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( diff --git a/test/chains.jl b/test/chains.jl index d1179b1a..04f5a5b8 100644 --- a/test/chains.jl +++ b/test/chains.jl @@ -53,11 +53,11 @@ Base.convert(::Type{ConvertedChain}, chain::SamplingOutput) = ConvertedChain(cha ) @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, opts... + 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