1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
use rand::{prelude::StdRng, Rng, SeedableRng};
use rayon::prelude::*;
use std::thread::JoinHandle;
use thiserror::Error;
use crate::{
adapt_strategy::{
DualAverageSettings, GradDiagStrategy, GradDiagOptions
},
cpu_potential::EuclideanPotential,
mass_matrix::DiagMassMatrix,
nuts::{Chain, NutsChain, NutsError, NutsOptions, SampleStats},
CpuLogpFunc,
};
#[derive(Clone, Copy)]
pub struct SamplerArgs {
pub num_tune: u64,
pub maxdepth: u64,
pub store_gradient: bool,
pub max_energy_error: f64,
pub step_size_adapt: DualAverageSettings,
pub mass_matrix_adapt: GradDiagOptions,
}
impl Default for SamplerArgs {
fn default() -> Self {
Self {
num_tune: 1000,
maxdepth: 10,
max_energy_error: 1000f64,
store_gradient: false,
step_size_adapt: DualAverageSettings::default(),
mass_matrix_adapt: GradDiagOptions::default(),
}
}
}
pub trait InitPointFunc {
fn new_init_point<R: Rng + ?Sized>(&mut self, rng: &mut R, out: &mut [f64]);
}
#[non_exhaustive]
#[derive(Error, Debug)]
pub enum ParallelSamplingError {
#[error("Could not send sample to controller thread")]
ChannelClosed(),
#[error("Nuts failed because of unrecoverable logp function error: {source}")]
NutsError {
#[from]
source: NutsError,
},
#[error("Initialization of first point failed")]
InitError { source: NutsError },
#[error("Timeout occured while waiting for next sample")]
Timeout,
#[error("Drawing sample paniced")]
Panic,
#[error("Creating a logp function failed")]
LogpFuncCreation {
#[from]
source: Box<dyn std::error::Error + Send + Sync>,
},
}
pub type ParallelChainResult = Result<(), ParallelSamplingError>;
pub trait CpuLogpFuncMaker: Send + Sync {
type Func: CpuLogpFunc;
fn make_logp_func(&self) -> Result<Self::Func, Box<dyn std::error::Error + Send + Sync>>;
fn dim(&self) -> usize;
}
pub fn sample_parallel<F: CpuLogpFuncMaker + 'static, I: InitPointFunc>(
logp_func_maker: F,
init_point_func: &mut I,
settings: SamplerArgs,
n_chains: u64,
n_draws: u64,
seed: u64,
n_try_init: u64,
) -> Result<
(
JoinHandle<Vec<ParallelChainResult>>,
crossbeam::channel::Receiver<(Box<[f64]>, Box<dyn SampleStats>)>,
),
ParallelSamplingError,
> {
let ndim = logp_func_maker.dim();
let mut func = logp_func_maker.make_logp_func()?;
assert!(ndim == func.dim());
let draws = settings.num_tune + n_draws;
let mut rng = StdRng::seed_from_u64(seed.wrapping_sub(1));
let mut points: Vec<Result<(Box<[f64]>, Box<[f64]>), <F::Func as CpuLogpFunc>::Err>> = (0
..n_chains)
.map(|_| {
let mut position = vec![0.; ndim];
let mut grad = vec![0.; ndim];
init_point_func.new_init_point(&mut rng, &mut position);
let mut error = None;
for _ in 0..n_try_init {
match func.logp(&mut position, &mut grad) {
Err(e) => error = Some(e),
Ok(_) => {
error = None;
break;
}
}
}
match error {
Some(e) => Err(e),
None => Ok((position.into(), grad.into())),
}
})
.collect();
let points: Result<Vec<(Box<[f64]>, Box<[f64]>)>, _> = points.drain(..).collect();
let points = points.map_err(|e| ParallelSamplingError::InitError {
source: NutsError::LogpFailure(Box::new(e)),
})?;
let (sender, receiver) = crossbeam::channel::bounded(128);
let handle = std::thread::spawn(move || {
let results: Vec<Result<(), ParallelSamplingError>> = points
.into_par_iter()
.with_max_len(1)
.enumerate()
.map_with(sender, |sender, (chain, point)| {
let func = logp_func_maker.make_logp_func()?;
let mut sampler = new_sampler(
func,
settings,
chain as u64,
seed.wrapping_add(chain as u64),
);
sampler.set_position(&point.0)?;
for _ in 0..draws {
let (point2, info) = sampler.draw()?;
sender
.send((point2, Box::new(info) as Box<dyn SampleStats>))
.map_err(|_| ParallelSamplingError::ChannelClosed())?;
}
Ok(())
})
.collect();
results
});
Ok((handle, receiver))
}
pub fn new_sampler<F: CpuLogpFunc>(
logp: F,
settings: SamplerArgs,
chain: u64,
seed: u64,
) -> impl Chain {
use crate::nuts::AdaptStrategy;
let num_tune = settings.num_tune;
let strategy = GradDiagStrategy::new(settings.mass_matrix_adapt, num_tune, logp.dim());
let mass_matrix = DiagMassMatrix::new(logp.dim());
let max_energy_error = settings.max_energy_error;
let potential = EuclideanPotential::new(logp, mass_matrix, max_energy_error, 1f64);
let options = NutsOptions {
maxdepth: settings.maxdepth,
store_gradient: settings.store_gradient,
};
let rng = rand::rngs::SmallRng::seed_from_u64(seed);
NutsChain::new(potential, strategy, options, rng, chain)
}
pub fn sample_sequentially<F: CpuLogpFunc>(
logp: F,
settings: SamplerArgs,
start: &[f64],
draws: u64,
chain: u64,
seed: u64,
) -> Result<impl Iterator<Item = Result<(Box<[f64]>, impl SampleStats), NutsError>>, NutsError> {
let mut sampler = new_sampler(logp, settings, chain, seed);
sampler.set_position(start)?;
Ok((0..draws).into_iter().map(move |_| sampler.draw()))
}
pub struct JitterInitFunc {
mu: Option<Box<[f64]>>,
}
impl JitterInitFunc {
pub fn new() -> JitterInitFunc {
JitterInitFunc { mu: None }
}
pub fn new_with_mean(mu: Box<[f64]>) -> Self {
Self { mu: Some(mu) }
}
}
impl InitPointFunc for JitterInitFunc {
fn new_init_point<R: Rng + ?Sized>(&mut self, rng: &mut R, out: &mut [f64]) {
rng.fill(out);
if self.mu.is_none() {
out.iter_mut().for_each(|val| *val = 2. * *val - 1.);
} else {
let mu = self.mu.as_ref().unwrap();
out.iter_mut()
.zip(mu.iter().copied())
.for_each(|(val, mu)| *val = 2. * *val - 1. + mu);
}
}
}
pub mod test_logps {
use crate::{cpu_potential::CpuLogpFunc, nuts::LogpError, CpuLogpFuncMaker};
use multiversion::multiversion;
use thiserror::Error;
#[derive(Clone)]
pub struct NormalLogp {
dim: usize,
mu: f64,
}
impl CpuLogpFuncMaker for NormalLogp {
type Func = Self;
fn make_logp_func(&self) -> Result<Self::Func, Box<dyn std::error::Error + Send + Sync>> {
Ok(self.clone())
}
fn dim(&self) -> usize {
self.dim
}
}
impl NormalLogp {
pub fn new(dim: usize, mu: f64) -> NormalLogp {
NormalLogp { dim, mu }
}
}
#[derive(Error, Debug)]
pub enum NormalLogpError {}
impl LogpError for NormalLogpError {
fn is_recoverable(&self) -> bool {
false
}
}
impl CpuLogpFunc for NormalLogp {
type Err = NormalLogpError;
fn dim(&self) -> usize {
self.dim
}
fn logp(&mut self, position: &[f64], gradient: &mut [f64]) -> Result<f64, NormalLogpError> {
let n = position.len();
assert!(gradient.len() == n);
#[cfg(feature = "simd_support")]
#[multiversion(targets("x86_64+avx+avx2+fma", "arm+neon"))]
fn logp_inner(mu: f64, position: &[f64], gradient: &mut [f64]) -> f64 {
use std::simd::f64x4;
use std::simd::SimdFloat;
let n = position.len();
assert!(gradient.len() == n);
let head_length = n - n % 4;
let (pos, pos_tail) = position.split_at(head_length);
let (grad, grad_tail) = gradient.split_at_mut(head_length);
let mu_splat = f64x4::splat(mu);
let mut logp = f64x4::splat(0f64);
for (p, g) in pos.chunks_exact(4).zip(grad.chunks_exact_mut(4)) {
let p = f64x4::from_slice(p);
let val = mu_splat - p;
logp = logp - val * val * f64x4::splat(0.5);
g.copy_from_slice(&val.to_array());
}
let mut logp_tail = 0f64;
for (p, g) in pos_tail.iter().zip(grad_tail.iter_mut()).take(3) {
let val = mu - p;
logp_tail -= val * val / 2.;
*g = val;
}
logp.reduce_sum() + logp_tail
}
#[cfg(not(feature = "simd_support"))]
#[multiversion(targets("x86_64+avx+avx2+fma", "arm+neon"))]
fn logp_inner(mu: f64, position: &[f64], gradient: &mut [f64]) -> f64 {
let n = position.len();
assert!(gradient.len() == n);
let mut logp = 0f64;
for (p, g) in position.iter().zip(gradient.iter_mut()) {
let val = mu - p;
logp -= val * val / 2.;
*g = val;
}
logp
}
let logp = logp_inner(self.mu, position, gradient);
Ok(logp)
}
}
}
#[cfg(test)]
mod tests {
use std::error::Error;
use crate::{
sample_parallel, sample_sequentially, test_logps::NormalLogp, CpuLogpFunc,
CpuLogpFuncMaker, JitterInitFunc, SampleStats, SamplerArgs,
};
use itertools::Itertools;
use pretty_assertions::assert_eq;
#[test]
fn sample_seq() {
let logp = NormalLogp::new(10, 0.1);
let mut settings = SamplerArgs::default();
settings.num_tune = 100;
let start = vec![0.2; 10];
let chain = sample_sequentially(logp.clone(), settings, &start, 200, 1, 42).unwrap();
let mut draws = chain.collect_vec();
assert_eq!(draws.len(), 200);
let draw0 = draws.remove(100).unwrap();
let (vals, stats) = draw0;
assert_eq!(vals.len(), 10);
assert_eq!(stats.chain(), 1);
assert_eq!(stats.draw(), 100);
assert!(stats
.to_vec()
.iter()
.any(|(key, _)| *key == "index_in_trajectory"));
let maker = logp;
let (handles, chains) =
sample_parallel(maker, &mut JitterInitFunc::new(), settings, 4, 100, 42, 10).unwrap();
let mut draws = chains.iter().collect_vec();
assert_eq!(draws.len(), 800);
assert!(handles.join().is_ok());
let draw0 = draws.remove(100);
let (vals, stats) = draw0;
assert_eq!(vals.len(), 10);
assert!(stats
.to_vec()
.iter()
.any(|(key, _)| *key == "index_in_trajectory"));
}
}