Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/CI.yml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ jobs:

- name: Run tests
uses: julia-actions/julia-runtest@v1
env:
JULIA_NUM_THREADS: 2
with:
project: ${{ matrix.pkg.dir }}
coverage: ${{ matrix.os == 'ubuntu-latest' && ((matrix.pkg.name == 'GeneralisedFilters' && matrix.version == '1') || (matrix.pkg.name == 'SSMProblems' && matrix.version == 'lts')) }}
Expand Down
8 changes: 8 additions & 0 deletions GeneralisedFilters/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# Changelog

## Unreleased

- Add `ThreadedExecution` for evaluating particle populations on several threads, selected
with the `execution` keyword of `ParticleFilter` and `BF`. RBPF, auxiliary particle
filters and CSMC ancestor sampling and backward simulation use the setting of their
particle filter. Results depend on the generator state and `blocksize` but not on the
number of threads. `SerialExecution()` remains the default and is unchanged.

## 0.5.0

This release changes the model interface and requires migration from 0.4.2. It targets
Expand Down
1 change: 1 addition & 0 deletions GeneralisedFilters/docs/make.jl
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ makedocs(;
"Models and conditioning" => "models/linear-gaussian.md",
"Particle Gibbs and Turing" => "inference.md",
"Recording filtering results" => "history.md",
"Multithreading" => "threading.md",
"Examples" =>
[joinpath("examples", f) for f in readdir(EXAMPLES_OUT) if endswith(f, ".md")],
"API reference" => "api.md",
Expand Down
3 changes: 2 additions & 1 deletion GeneralisedFilters/docs/src/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,8 @@ Read [Models and conditioning](models/linear-gaussian.md) to define a hierarchic
and see how fixing an outer trajectory gives a conditional inner model. Then follow
[Particle Gibbs and Turing](inference.md) for joint trajectory and parameter inference.
Read [Recording filtering results](history.md) for manual loops and particle ancestry
storage. The **Examples** section works through trend inflation with stochastic volatility
storage. [Multithreading](threading.md) explains how to evaluate particles in parallel.
The **Examples** section works through trend inflation with stochastic volatility
and benchmarks filters using static arrays.

The [API reference](api.md) lists the available types and operations. Existing users
Expand Down
71 changes: 71 additions & 0 deletions GeneralisedFilters/docs/src/threading.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# Multithreading

Particle filters can evaluate their particles on several threads. Start Julia with more
than one thread, for example `julia --threads=auto`, and select `ThreadedExecution` for the
particle filter:

```julia
pf = BF(10_000; threshold=0.5, execution=ThreadedExecution())
state, loglikelihood = GeneralisedFilters.filter(rng, model, pf, observations)
```

Filters built from a particle filter use its setting. For example,
`RBPF(BF(1_000; execution=ThreadedExecution(blocksize=8)), KF())` evaluates its
Rao–Blackwellised particles in parallel. Wrapping it in `AuxiliaryParticleFilter` also
parallelises the lookahead, and wrapping it in `ConditionalSMC` also parallelises the
`AncestorSampling()` and `BackwardSimulation()` weights. The default,
`SerialExecution()`, evaluates particles in order on the calling task.

## What runs in parallel

Initialisation, prediction, observation updates, auxiliary lookahead weights and ancestor
sampling or backward simulation weights are evaluated in parallel. Resampling, weight
normalisation and particle history storage remain serial. The speed-up is therefore
largest when each particle is expensive to update, as for Rao–Blackwellised particles or
costly nonlinear models. When each particle update takes only a few nanoseconds, the
serial steps limit the gain.

## Reproducibility

Particles are evaluated in consecutive blocks of `blocksize` particles, 32 by default. Each
block draws from its own random number generator, derived from a single draw of the
generator passed to the filter. For a given generator state, number of particles and
`blocksize`, results are the same for any number of threads or tasks. Changing
`blocksize` changes the random draws. Threaded and serial runs use different random
streams, so their results differ, but calculations that draw no randomness, such as
observation updates and ancestor weights, give identical values.

The block size is also the smallest amount of work given to a task. Prefer larger blocks,
such as 1024, when each particle is cheap, and smaller blocks, such as 4 to 32, for
Rao–Blackwellised particles. `ThreadedExecution(ntasks=4)` limits the number of tasks
without changing the results.

## Requirements on model code

With threaded execution, model code runs concurrently for different particles:

- Draw randomness only from the generator passed to `simulate` or a proposal, never from a
captured or global generator.
- Do not mutate state shared between particles, such as a captured buffer or cache.
- Every particle must have the same concrete type. Threaded evaluation throws an
`ArgumentError` otherwise.

Allocation in model code limits scaling, because threads contend for the garbage
collector. StaticArrays avoid this for small states. Models using BLAS on heap arrays
should usually call `LinearAlgebra.BLAS.set_num_threads(1)` to avoid oversubscribing the
processor.

## Automatic differentiation

ForwardDiff differentiates through threaded evaluation. Reverse-mode differentiation with
Mooncake does not support threads and raises an error: use `SerialExecution()` for
particle objectives differentiated in reverse mode. Particle Gibbs does not differentiate
through the particle filter, so its CSMC sampler can use threaded execution with either
backend.

## Independent filters

Separate filters or chains can also run concurrently. AbstractMCMC's `MCMCThreads()` runs
several chains in parallel, and independent calls to `filter` can run in separate tasks
if each receives its own generator. Threaded execution within a filter uses Julia tasks,
so it can be combined with these approaches.
4 changes: 4 additions & 0 deletions GeneralisedFilters/src/GeneralisedFilters.jl
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ include("gaussian.jl")
include("containers.jl")
include("resamplers.jl")

## EXECUTION ###############################################################################

include("execution.jl")

## MODEL LAYER #############################################################################

include("models/interface.jl")
Expand Down
13 changes: 8 additions & 5 deletions GeneralisedFilters/src/algorithms/csmc.jl
Original file line number Diff line number Diff line change
Expand Up @@ -351,8 +351,11 @@ function _csmc_sample(
state = resample(rng, rs, state)
else
ref_as = _build_ancestor_ref(ref_state, back_liks, t)
as_weights = map(state.particles) do particle
return ancestor_weight(particle, model.dyn, pf, t, ref_as)
# A fresh binding: `state` is reassigned in this function, so capturing it
# in the closure would box it.
particles = state.particles
as_weights = _population_map(execution(pf), length(particles)) do i
return ancestor_weight(particles[i], model.dyn, pf, t, ref_as)
end
ancestor_idx = StatsBase.sample(rng, StatsBase.Weights(softmax(as_weights)))
# Draw the WHOLE conditional law given the newly selected ancestor. For
Expand Down Expand Up @@ -458,7 +461,7 @@ function _csmc_sample(

for t in (K - 1):-1:1
ref_next = _build_bs_ref(xs[t + 1], back_lik)
backward_ws = map(1:N) do i
backward_ws = _population_map(execution(pf), N) do i
return ancestor_weight(
Particle(container, t, i), model.dyn, pf, t + 1, ref_next
)
Expand All @@ -481,8 +484,8 @@ function _csmc_sample(

# Time 0: backward step from t=1 to initial particles.
ref_at_1 = _build_bs_ref(xs[1], back_lik)
backward_ws = map(init_state.particles) do particle
return ancestor_weight(particle, model.dyn, pf, 1, ref_at_1)
backward_ws = _population_map(execution(pf), N) do i
return ancestor_weight(init_state.particles[i], model.dyn, pf, 1, ref_at_1)
end
idx = StatsBase.sample(rng, StatsBase.Weights(softmax(backward_ws)))
x0 = container.initial_states[idx]
Expand Down
78 changes: 60 additions & 18 deletions GeneralisedFilters/src/algorithms/particles.jl
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,22 @@ end
function num_particles end
function resampler end

"""
execution(algo::AbstractParticleFilter) -> AbstractExecution

The [`AbstractExecution`](@ref) used to evaluate the particle population. Particle filters
without an execution setting evaluate serially.
"""
execution(::AbstractParticleFilter) = SerialExecution()

function initialise(
rng::AbstractRNG,
prior::StatePrior,
algo::AbstractParticleFilter;
ref_state::Union{Nothing,AbstractVector}=nothing,
)
N = num_particles(algo)
particles = map(1:N) do i
particles = _population_map(execution(algo), rng, N) do rng, i
ref = !isnothing(ref_state) && i == 1 ? _trajectory_state(ref_state, 0) : nothing
return initialise_particle(rng, prior, algo, ref)
end
Expand All @@ -59,15 +67,9 @@ function predict(
observation;
ref_state::Union{Nothing,AbstractVector}=nothing,
)
particles = map(1:num_particles(algo)) do i
particle = state.particles[i]
ref = if !isnothing(ref_state) && i == 1
_trajectory_state(ref_state, iter)
else
nothing
end
return predict_particle(rng, dyn, algo, iter, particle, observation, ref)
end
particles = _predict_particles(
rng, dyn, algo, iter, state.particles, observation, ref_state
)

# Preserve the incoming weight normalizer; guided proposal corrections belong
# to the new weights and must not be subtracted from the evidence increment.
Expand All @@ -78,39 +80,77 @@ function predict(
)
end

# Population traversal is the execution boundary. The scalar hooks retain their
# dispatch and RNG order; batched storage can select bulk execution here.
function _predict_particles(
rng::AbstractRNG,
dyn::LatentDynamics,
algo::AbstractParticleFilter,
iter::Integer,
particles,
observation,
ref_state,
)
return _population_map(execution(algo), rng, num_particles(algo)) do rng, i
particle = particles[i]
ref = if !isnothing(ref_state) && i == 1
_trajectory_state(ref_state, iter)
else
nothing
end
return predict_particle(rng, dyn, algo, iter, particle, observation, ref)
end
end

function update(
obs::ObservationProcess,
algo::AbstractParticleFilter,
iter::Integer,
state::ParticleDistribution,
observation,
)
particles = map(state.particles) do particle
return update_particle(obs, algo, iter, particle, observation)
end
particles = _update_particles(obs, algo, iter, state.particles, observation)
new_state, ll_increment = marginalise!(state, particles)

return new_state, ll_increment
end

struct ParticleFilter{RS,PT} <: AbstractParticleFilter
function _update_particles(
obs::ObservationProcess,
algo::AbstractParticleFilter,
iter::Integer,
particles,
observation,
)
return _population_map(execution(algo), length(particles)) do i
return update_particle(obs, algo, iter, particles[i], observation)
end
end

struct ParticleFilter{RS,PT,EX<:AbstractExecution} <: AbstractParticleFilter
N::Int
resampler::RS
proposal::PT
execution::EX
end

const PF = ParticleFilter

function ParticleFilter(
N::Integer, proposal::PT; threshold::Real=1.0, resampler::AbstractResampler=Systematic()
N::Integer,
proposal::PT;
threshold::Real=1.0,
resampler::AbstractResampler=Systematic(),
execution::AbstractExecution=SerialExecution(),
) where {PT<:AbstractProposal}
N > 0 || throw(ArgumentError("particle count must be positive"))
conditional_resampler = ESSResampler(threshold, resampler)
return ParticleFilter(N, conditional_resampler, proposal)
return ParticleFilter(N, conditional_resampler, proposal, execution)
end

num_particles(algo::ParticleFilter) = algo.N
resampler(algo::ParticleFilter) = algo.resampler
execution(algo::ParticleFilter) = algo.execution

function initialise_particle(
rng::AbstractRNG, prior::StatePrior, algo::ParticleFilter, ref_state
Expand Down Expand Up @@ -287,6 +327,7 @@ end

resampler(algo::AuxiliaryParticleFilter) = resampler(algo.pf)
num_particles(algo::AuxiliaryParticleFilter) = num_particles(algo.pf)
execution(algo::AuxiliaryParticleFilter) = execution(algo.pf)

function initialise(
rng::AbstractRNG,
Expand Down Expand Up @@ -325,9 +366,10 @@ end
function _step_resampler(
rng, model, algo::AuxiliaryParticleFilter, iter, state, observation
)
log_ηs = map(state.particles) do particle
particles = state.particles
log_ηs = _population_map(execution(algo), rng, length(particles)) do rng, i
return compute_logeta(
rng, algo.weight_strategy, model, algo.pf, iter, particle.state, observation
rng, algo.weight_strategy, model, algo.pf, iter, particles[i].state, observation
)
end
return AuxiliaryResampler(resampler(algo), log_ηs)
Expand Down
1 change: 1 addition & 0 deletions GeneralisedFilters/src/algorithms/rbpf.jl
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ end

num_particles(algo::RBPF) = num_particles(algo.pf)
resampler(algo::RBPF) = resampler(algo.pf)
execution(algo::RBPF) = execution(algo.pf)

function initialise_particle(
rng::AbstractRNG, prior::HierarchicalPrior, algo::RBPF, ref_state
Expand Down
Loading
Loading