Skip to main content

Tpe

Struct Tpe 

pub struct Tpe { /* private fields */ }
Expand description

A Tree-structured Parzen Estimator sampler.

Construct one with Tpe::new (Optuna-matching defaults) and hand it to a study through StudyBuilder::sampler. The knobs below are the only configuration; everything else is derived from the study’s history on each decision. See the module-level documentation for the algorithm.

use atune_core::sampler::Tpe;
use atune_core::space::{Distribution, ParamSpec, SpaceSchema};
use atune_core::study::{Budget, Study, StudyConfig};
use std::sync::Arc;

let space = SpaceSchema::new([
    ParamSpec::new("x", Distribution::float(-5.0, 5.0).unwrap()).unwrap(),
    ParamSpec::new("y", Distribution::float(-5.0, 5.0).unwrap()).unwrap(),
])
.unwrap();

let study = Study::builder()
    .sampler(Arc::new(Tpe::new()))
    .budget(Budget::trials(60))
    .create(StudyConfig::new("sphere").with_seed(0).with_space(space))
    .unwrap();

study
    .optimize(|ctx| {
        let x = ctx.suggest_f64("x", -5.0..=5.0, atune_core::space::Scale::Linear)?;
        let y = ctx.suggest_f64("y", -5.0..=5.0, atune_core::space::Scale::Linear)?;
        Ok((x * x + y * y).into())
    })
    .unwrap();

// TPE concentrates near the origin, so the best is well below a random draw.
let best = study.best_trial().unwrap().unwrap();
assert!(best.single_objective_value().unwrap() < 1.0);

Implementations§

§

impl Tpe

pub const fn new() -> Self

A TPE sampler with Optuna-matching defaults.

n_startup_trials = 10, n_ei_candidates = 24, gamma = 0.25, prior_weight = 1.0, constant liar on.

pub const fn with_startup_trials(self, n: usize) -> Self

Sets how many initial trials are sampled uniformly before TPE engages.

Too few and the first density models are fit on noise; the default of 10 matches Optuna.

pub const fn with_ei_candidates(self, n: usize) -> Self

Sets how many candidate points are scored per decision.

More candidates sharpen the argmax at linear cost; the default is 24.

pub const fn with_gamma(self, gamma: f64) -> Self

Sets the split quantile factor gamma in n_good = ceil(gamma·√n).

Larger gamma widens the “good” set. The raw value is retained by this infallible builder; it must be finite and in (0, 1] when sampling.

pub const fn with_prior_weight(self, weight: f64) -> Self

Sets the prior weight used in every Parzen estimator.

pub const fn with_constant_liar(self, on: bool) -> Self

Turns the pending-aware constant liar on or off.

On by default. With it off, running trials are ignored and parallel workers no longer repel from one another — useful only for isolating the effect in a test.

Trait Implementations§

§

impl Clone for Tpe

§

fn clone(&self) -> Tpe

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl Copy for Tpe

§

impl Debug for Tpe

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
§

impl Default for Tpe

§

fn default() -> Self

Returns the “default value” for a type. Read more
§

impl PartialEq for Tpe

§

fn eq(&self, other: &Tpe) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
§

impl Sampler for Tpe

§

fn infer_relative_space(&self, study: &StudyView) -> Result<SpaceSchema>

The study’s declared space, or the intersection of the visible trials’ parameters for a define-by-run study.

Identical in shape to Random: a declared space is returned verbatim, and an inferred one keeps only the parameters every visible trial recorded compatibly, name-ordered. The group decomposition then runs inside sample_relative; for a co-occurring space it is a single group.

§Errors

Error::InvalidSpace if a recorded parameter name is empty, which no writer of this crate produces, or if one of the sampler’s configuration knobs is invalid.

§

fn sample_relative( &self, study: &StudyView, trial: &TrialMeta, space: &SpaceSchema, ) -> Result<Assignment>

Samples the joint space with multivariate, group-decomposed TPE.

Each co-occurrence group is modelled jointly and the constant liar folds in the pending trials; a group short of n_startup_trials completed observations (including the whole study during startup) is drawn uniformly. Every returned value lies in its declared support, because it is produced through Distribution::from_unit or a valid choice index.

§Errors

Error::InvalidSpace if a declared distribution is malformed or one of the sampler’s configuration knobs is invalid.

§

fn sample_independent( &self, study: &StudyView, trial: &TrialMeta, name: &str, dist: &Distribution, ) -> Result<ParamValue>

Samples one parameter with univariate TPE — the fallback for a parameter the relative space did not cover, or one outside any joint group.

Uses the same joint split (by trial objective) and the same constant liar as the relative path, over the trials that recorded this parameter. Below the startup threshold it is the uniform Random draw.

§Errors

Error::InvalidSpace if dist is malformed or one of the sampler’s configuration knobs is invalid.

§

fn state(&self) -> Result<Option<StateBlob>>

A no-op, and deliberately so: TPE holds no persistable state.

Everything it knows is recomputed from the StudyView each decision, so there is nothing to write. See the module-level documentation — this is what makes a journal reopen continue identically.

§Errors

Never.

§

fn reseed(&self, _seed: u64)

A no-op.

TPE derives its candidate RNG from TrialMeta::sampler_seed, so there is no auxiliary randomness for a reseed to move — the same argument Random::reseed documents. Change the study seed to change what a study samples.

§

fn after_trial(&self, study: &StudyView, trial: &FrozenTrial) -> Result<()>

Called once a trial reaches a terminal state. Read more
§

fn snapshots_space(&self) -> bool

Whether this sampler enumerates a snapshot of the space it was constructed with, rather than the space each ask presents. Read more
§

fn restore_state(&self, blob: &SamplerState) -> Result<()>

Restores a sampler from a previously persisted blob. Read more
§

impl StructuralPartialEq for Tpe

Auto Trait Implementations§

§

impl Freeze for Tpe

§

impl RefUnwindSafe for Tpe

§

impl Send for Tpe

§

impl Sync for Tpe

§

impl Unpin for Tpe

§

impl UnsafeUnpin for Tpe

§

impl UnwindSafe for Tpe

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more