Skip to main content

Trial

Struct Trial 

Source
pub struct Trial { /* private fields */ }
Expand description

A trial represents a single evaluation of the objective function.

Each trial has a unique ID and stores the sampled parameters along with their distributions. The trial progresses through states: Running -> Complete/Failed.

Trials use a sampler to generate parameter values. When created through Study::create_trial(), the trial receives the study’s sampler and access to the history of completed trials for informed sampling.

Implementations§

Source§

impl Trial

Source

pub fn new(id: u64) -> Self

Creates a new trial with the given ID.

The trial starts in the Running state with no parameters sampled. This constructor creates a trial without a sampler, which will use local random sampling for suggest_* methods.

For trials that use the study’s sampler, use Trial::with_sampler instead.

§Arguments
  • id - A unique identifier for this trial.
§Examples
use optimizer::Trial;

let trial = Trial::new(0);
assert_eq!(trial.id(), 0);
Source

pub fn id(&self) -> u64

Returns the unique ID of this trial.

Source

pub fn state(&self) -> TrialState

Returns the current state of this trial.

Source

pub fn params(&self) -> &HashMap<String, ParamValue>

Returns a reference to the sampled parameters.

Source

pub fn distributions(&self) -> &HashMap<String, Distribution>

Returns a reference to the parameter distributions.

Source

pub fn suggest_float( &mut self, name: impl Into<String>, low: f64, high: f64, ) -> Result<f64>

Suggests a float parameter with the given bounds.

If the parameter has already been sampled with the same bounds, the cached value is returned. If the parameter was sampled with different bounds, a ParameterConflict error is returned.

§Arguments
  • name - The name of the parameter.
  • low - The lower bound (inclusive).
  • high - The upper bound (inclusive).
§Errors

Returns InvalidBounds if low > high. Returns ParameterConflict if the parameter was previously sampled with different bounds.

§Examples
use optimizer::Trial;

let mut trial = Trial::new(0);
let x = trial.suggest_float("x", 0.0, 1.0).unwrap();
assert!(x >= 0.0 && x <= 1.0);

// Calling again with same bounds returns cached value
let x2 = trial.suggest_float("x", 0.0, 1.0).unwrap();
assert_eq!(x, x2);
Source

pub fn suggest_float_log( &mut self, name: impl Into<String>, low: f64, high: f64, ) -> Result<f64>

Suggests a float parameter sampled on a logarithmic scale.

The value is sampled uniformly in log space, which is useful for parameters that span multiple orders of magnitude (e.g., learning rates).

If the parameter has already been sampled with the same bounds and log_scale=true, the cached value is returned. If the parameter was sampled with different configuration, a ParameterConflict error is returned.

§Arguments
  • name - The name of the parameter.
  • low - The lower bound (inclusive, must be positive).
  • high - The upper bound (inclusive).
§Errors

Returns InvalidLogBounds if low <= 0. Returns InvalidBounds if low > high. Returns ParameterConflict if the parameter was previously sampled with different configuration.

§Examples
use optimizer::Trial;

let mut trial = Trial::new(0);
let lr = trial
    .suggest_float_log("learning_rate", 1e-5, 1e-1)
    .unwrap();
assert!(lr >= 1e-5 && lr <= 1e-1);

// Calling again with same bounds returns cached value
let lr2 = trial
    .suggest_float_log("learning_rate", 1e-5, 1e-1)
    .unwrap();
assert_eq!(lr, lr2);
Source

pub fn suggest_float_step( &mut self, name: impl Into<String>, low: f64, high: f64, step: f64, ) -> Result<f64>

Suggests a float parameter that snaps to a step grid.

The value is sampled from the discrete set {low, low + step, low + 2*step, …} where each value is <= high.

If the parameter has already been sampled with the same configuration, the cached value is returned. If the parameter was sampled with different configuration, a ParameterConflict error is returned.

§Arguments
  • name - The name of the parameter.
  • low - The lower bound (inclusive).
  • high - The upper bound (inclusive).
  • step - The step size (must be positive).
§Errors

Returns InvalidStep if step <= 0. Returns InvalidBounds if low > high. Returns ParameterConflict if the parameter was previously sampled with different configuration.

§Examples
use optimizer::Trial;

let mut trial = Trial::new(0);
let x = trial.suggest_float_step("x", 0.0, 1.0, 0.25).unwrap();
// x will be one of: 0.0, 0.25, 0.5, 0.75, 1.0
assert!(x >= 0.0 && x <= 1.0);
assert!((x / 0.25).fract().abs() < 1e-10 || (x / 0.25).fract().abs() > 1.0 - 1e-10);

// Calling again with same bounds returns cached value
let x2 = trial.suggest_float_step("x", 0.0, 1.0, 0.25).unwrap();
assert_eq!(x, x2);
Source

pub fn suggest_int( &mut self, name: impl Into<String>, low: i64, high: i64, ) -> Result<i64>

Suggests an integer parameter with the given bounds.

The value is sampled uniformly from the range [low, high] inclusive.

If the parameter has already been sampled with the same bounds, the cached value is returned. If the parameter was sampled with different bounds, a ParameterConflict error is returned.

§Arguments
  • name - The name of the parameter.
  • low - The lower bound (inclusive).
  • high - The upper bound (inclusive).
§Errors

Returns InvalidBounds if low > high. Returns ParameterConflict if the parameter was previously sampled with different bounds.

§Examples
use optimizer::Trial;

let mut trial = Trial::new(0);
let n = trial.suggest_int("n_layers", 1, 10).unwrap();
assert!(n >= 1 && n <= 10);

// Calling again with same bounds returns cached value
let n2 = trial.suggest_int("n_layers", 1, 10).unwrap();
assert_eq!(n, n2);
Source

pub fn suggest_int_log( &mut self, name: impl Into<String>, low: i64, high: i64, ) -> Result<i64>

Suggests an integer parameter sampled on a logarithmic scale.

The value is sampled uniformly in log space, which is useful for parameters that span multiple orders of magnitude (e.g., batch sizes).

If the parameter has already been sampled with the same bounds and log_scale=true, the cached value is returned. If the parameter was sampled with different configuration, a ParameterConflict error is returned.

§Arguments
  • name - The name of the parameter.
  • low - The lower bound (inclusive, must be >= 1).
  • high - The upper bound (inclusive).
§Errors

Returns InvalidLogBounds if low < 1. Returns InvalidBounds if low > high. Returns ParameterConflict if the parameter was previously sampled with different configuration.

§Examples
use optimizer::Trial;

let mut trial = Trial::new(0);
let batch_size = trial.suggest_int_log("batch_size", 1, 1024).unwrap();
assert!(batch_size >= 1 && batch_size <= 1024);

// Calling again with same bounds returns cached value
let batch_size2 = trial.suggest_int_log("batch_size", 1, 1024).unwrap();
assert_eq!(batch_size, batch_size2);
Source

pub fn suggest_int_step( &mut self, name: impl Into<String>, low: i64, high: i64, step: i64, ) -> Result<i64>

Suggests an integer parameter that snaps to a step grid.

The value is sampled from the discrete set {low, low + step, low + 2*step, …} where each value is <= high.

If the parameter has already been sampled with the same configuration, the cached value is returned. If the parameter was sampled with different configuration, a ParameterConflict error is returned.

§Arguments
  • name - The name of the parameter.
  • low - The lower bound (inclusive).
  • high - The upper bound (inclusive).
  • step - The step size (must be positive).
§Errors

Returns InvalidStep if step <= 0. Returns InvalidBounds if low > high. Returns ParameterConflict if the parameter was previously sampled with different configuration.

§Examples
use optimizer::Trial;

let mut trial = Trial::new(0);
let n = trial
    .suggest_int_step("n_estimators", 100, 500, 50)
    .unwrap();
// n will be one of: 100, 150, 200, 250, 300, 350, 400, 450, 500
assert!(n >= 100 && n <= 500);
assert!((n - 100) % 50 == 0);

// Calling again with same bounds returns cached value
let n2 = trial
    .suggest_int_step("n_estimators", 100, 500, 50)
    .unwrap();
assert_eq!(n, n2);
Source

pub fn suggest_categorical<T: Clone>( &mut self, name: impl Into<String>, choices: &[T], ) -> Result<T>

Suggests a categorical parameter from the given choices.

The value is selected uniformly at random from the provided choices. Internally, the index of the selected choice is stored.

If the parameter has already been sampled with the same number of choices, the cached value (same index) is returned. If the parameter was sampled with a different number of choices, a ParameterConflict error is returned.

§Arguments
  • name - The name of the parameter.
  • choices - A slice of choices to select from.
§Type Parameters
  • T - The type of the choices. Only requires Clone.
§Errors

Returns EmptyChoices if choices is empty. Returns ParameterConflict if the parameter was previously sampled with a different number of choices.

§Examples
use optimizer::Trial;

let mut trial = Trial::new(0);
let optimizer = trial
    .suggest_categorical("optimizer", &["sgd", "adam", "rmsprop"])
    .unwrap();
assert!(["sgd", "adam", "rmsprop"].contains(&optimizer));

// Calling again with same choices returns cached value
let optimizer2 = trial
    .suggest_categorical("optimizer", &["sgd", "adam", "rmsprop"])
    .unwrap();
assert_eq!(optimizer, optimizer2);

Trait Implementations§

Source§

impl Clone for Trial

Source§

fn clone(&self) -> Trial

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for Trial

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Trial

§

impl !RefUnwindSafe for Trial

§

impl Send for Trial

§

impl Sync for Trial

§

impl Unpin for Trial

§

impl !UnwindSafe for Trial

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
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.

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.

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.
Source§

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

Source§

fn vzip(self) -> V