|
| 1 | +//! Example demonstrating the Adam optimizer for step size adaptation. |
| 2 | +//! |
| 3 | +//! This example shows how to use the Adam optimizer instead of dual averaging |
| 4 | +//! for adapting the step size in NUTS. |
| 5 | +
|
| 6 | +use nuts_rs::{ |
| 7 | + AdamOptions, Chain, CpuLogpFunc, CpuMath, DiagGradNutsSettings, LogpError, Settings, |
| 8 | + StepSizeAdaptMethod, |
| 9 | +}; |
| 10 | +use thiserror::Error; |
| 11 | + |
| 12 | +// Define a function that computes the unnormalized posterior density |
| 13 | +// and its gradient. |
| 14 | +#[derive(Debug)] |
| 15 | +struct PosteriorDensity {} |
| 16 | + |
| 17 | +// The density might fail in a recoverable or non-recoverable manner... |
| 18 | +#[derive(Debug, Error)] |
| 19 | +enum PosteriorLogpError {} |
| 20 | +impl LogpError for PosteriorLogpError { |
| 21 | + fn is_recoverable(&self) -> bool { |
| 22 | + false |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +impl CpuLogpFunc for PosteriorDensity { |
| 27 | + type LogpError = PosteriorLogpError; |
| 28 | + |
| 29 | + // Only used for transforming adaptation. |
| 30 | + type TransformParams = (); |
| 31 | + |
| 32 | + // We define a 10 dimensional normal distribution |
| 33 | + fn dim(&self) -> usize { |
| 34 | + 10 |
| 35 | + } |
| 36 | + |
| 37 | + // The normal likelihood with mean 3 and its gradient. |
| 38 | + fn logp(&mut self, position: &[f64], grad: &mut [f64]) -> Result<f64, Self::LogpError> { |
| 39 | + let mu = 3f64; |
| 40 | + let logp = position |
| 41 | + .iter() |
| 42 | + .copied() |
| 43 | + .zip(grad.iter_mut()) |
| 44 | + .map(|(x, grad)| { |
| 45 | + let diff = x - mu; |
| 46 | + *grad = -diff; |
| 47 | + -diff * diff / 2f64 |
| 48 | + }) |
| 49 | + .sum(); |
| 50 | + return Ok(logp); |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +fn main() { |
| 55 | + println!("Running NUTS with Adam step size adaptation..."); |
| 56 | + |
| 57 | + // Create sampler settings with Adam optimizer |
| 58 | + let mut settings = DiagGradNutsSettings::default(); |
| 59 | + |
| 60 | + // Configure for Adam adaptation |
| 61 | + settings |
| 62 | + .adapt_options |
| 63 | + .step_size_settings |
| 64 | + .adapt_options |
| 65 | + .method = StepSizeAdaptMethod::Adam; |
| 66 | + |
| 67 | + // Set Adam options |
| 68 | + let adam_options = AdamOptions { |
| 69 | + beta1: 0.9, |
| 70 | + beta2: 0.999, |
| 71 | + epsilon: 1e-8, |
| 72 | + learning_rate: 0.05, |
| 73 | + }; |
| 74 | + |
| 75 | + settings.adapt_options.step_size_settings.adapt_options.adam = adam_options; |
| 76 | + |
| 77 | + // Standard MCMC settings |
| 78 | + settings.num_tune = 1000; |
| 79 | + settings.num_draws = 1000; |
| 80 | + settings.maxdepth = 10; |
| 81 | + |
| 82 | + // Create the posterior density function |
| 83 | + let logp_func = PosteriorDensity {}; |
| 84 | + let math = CpuMath::new(logp_func); |
| 85 | + |
| 86 | + // Initialize the sampler |
| 87 | + let chain = 0; |
| 88 | + let mut rng = rand::rng(); |
| 89 | + let mut sampler = settings.new_chain(chain, math, &mut rng); |
| 90 | + |
| 91 | + // Set initial position |
| 92 | + let initial_position = vec![0f64; 10]; |
| 93 | + sampler |
| 94 | + .set_position(&initial_position) |
| 95 | + .expect("Unrecoverable error during init"); |
| 96 | + |
| 97 | + // Collect samples |
| 98 | + let mut trace = vec![]; |
| 99 | + let mut stats = vec![]; |
| 100 | + |
| 101 | + // Sampling with progress reporting |
| 102 | + println!("Warmup phase:"); |
| 103 | + for i in 0..settings.num_tune { |
| 104 | + if i % 100 == 0 { |
| 105 | + println!("\rWarmup: {}/{}", i, settings.num_tune); |
| 106 | + } |
| 107 | + |
| 108 | + let (draw, info) = sampler.draw().expect("Unrecoverable error during sampling"); |
| 109 | + println!("{:?}", info.step_size); |
| 110 | + trace.push(draw); |
| 111 | + stats.push(info); |
| 112 | + } |
| 113 | + println!("\rWarmup: {}/{}", settings.num_tune, settings.num_tune); |
| 114 | + |
| 115 | + println!("\nSampling phase:"); |
| 116 | + for i in 0..settings.num_draws { |
| 117 | + if i % 100 == 0 { |
| 118 | + print!("\rSampling: {}/{}", i, settings.num_draws); |
| 119 | + } |
| 120 | + |
| 121 | + let (draw, info) = sampler.draw().expect("Unrecoverable error during sampling"); |
| 122 | + trace.push(draw); |
| 123 | + stats.push(info); |
| 124 | + } |
| 125 | + println!("\rSampling: {}/{}", settings.num_draws, settings.num_draws); |
| 126 | + |
| 127 | + // Calculate mean of samples (post-warmup) |
| 128 | + let warmup_samples = settings.num_tune as usize; |
| 129 | + let mut means = vec![0.0; 10]; |
| 130 | + |
| 131 | + for i in warmup_samples..trace.len() { |
| 132 | + for (j, mean) in means.iter_mut().enumerate() { |
| 133 | + *mean += trace[i][j]; |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + for mean in &mut means { |
| 138 | + *mean /= settings.num_draws as f64; |
| 139 | + } |
| 140 | + |
| 141 | + // Print results |
| 142 | + println!("\nResults after {} samples:", settings.num_draws); |
| 143 | + println!("Target mean: 3.0 for all dimensions"); |
| 144 | + println!("Estimated means:"); |
| 145 | + for (i, mean) in means.iter().enumerate() { |
| 146 | + println!("Dimension {}: {:.4}", i, mean); |
| 147 | + } |
| 148 | + |
| 149 | + // Print adaptation statistics |
| 150 | + let last_stats = &stats[stats.len() - 1]; |
| 151 | + println!("\nFinal adaptation statistics:"); |
| 152 | + println!("Step size: {:.6}", last_stats.step_size); |
| 153 | + // Note: the full acceptance stats are in the Progress struct, but we don't have direct access to mean_tree_accept |
| 154 | + println!("Number of steps: {}", last_stats.num_steps); |
| 155 | + |
| 156 | + println!("\nSampling completed successfully!"); |
| 157 | +} |
0 commit comments