Skip to main content

Sampler

Trait Sampler 

Source
pub trait Sampler: Send + Sync {
    // Required method
    fn sample(
        &self,
        distribution: &Distribution,
        trial_id: u64,
        history: &[CompletedTrial],
    ) -> ParamValue;
}
Expand description

Trait for pluggable parameter sampling strategies.

Samplers are responsible for generating parameter values based on the distribution and historical trial data. The trait requires Send + Sync to support concurrent and async optimization.

§Implementing a custom sampler

use optimizer::sampler::{Sampler, CompletedTrial};
use optimizer::distribution::Distribution;
use optimizer::param::ParamValue;

struct NoisySampler {
    noise_scale: f64,
    seed: u64,
}

impl Sampler for NoisySampler {
    fn sample(
        &self,
        distribution: &Distribution,
        trial_id: u64,
        history: &[CompletedTrial],
    ) -> ParamValue {
        // Find the best value seen so far, or fall back to the midpoint
        match distribution {
            Distribution::Float(fd) => {
                let center = if history.is_empty() {
                    (fd.low + fd.high) / 2.0
                } else {
                    history.iter()
                        .filter_map(|t| t.params.values().next())
                        .filter_map(|v| if let ParamValue::Float(f) = v { Some(*f) } else { None })
                        .next()
                        .unwrap_or((fd.low + fd.high) / 2.0)
                };
                let noise = (trial_id as f64 * 0.1).sin() * self.noise_scale;
                ParamValue::Float(center + noise)
            }
            Distribution::Int(id) => ParamValue::Int((id.low + id.high) / 2),
            Distribution::Categorical(cd) => ParamValue::Categorical(trial_id as usize % cd.n_choices),
        }
    }
}

See the module-level documentation for a comprehensive guide covering cold start handling, thread safety patterns, and testing.

Required Methods§

Source

fn sample( &self, distribution: &Distribution, trial_id: u64, history: &[CompletedTrial], ) -> ParamValue

Samples a parameter value from the given distribution.

§Arguments
  • distribution - The parameter distribution to sample from.
  • trial_id - The unique ID of the trial being sampled for.
  • history - Historical completed trials for informed sampling.
§Returns

A ParamValue sampled from the distribution.

Implementors§