From 3870b6f781e08f502c0a8579d4b505f76e608358 Mon Sep 17 00:00:00 2001 From: c-bata Date: Thu, 5 Nov 2026 13:17:19 +0900 Subject: [PATCH] Pass the trial queue to sampler callbacks --- rustuna_core/src/sampler.rs | 20 +++- rustuna_core/src/study.rs | 25 +++-- rustuna_core/src/trial.rs | 14 ++- rustuna_pyo3/rustuna/_protocols.py | 9 ++ rustuna_pyo3/rustuna/_rustuna.pyi | 17 ++++ rustuna_pyo3/rustuna/converter/_sampler.py | 20 +++- rustuna_pyo3/src/sampler/cmaes.rs | 28 ++++-- rustuna_pyo3/src/sampler/nsgaii.rs | 24 +++-- rustuna_pyo3/src/sampler/random.rs | 22 +++-- rustuna_pyo3/src/sampler/to_rust.rs | 51 +++++++++- rustuna_pyo3/src/sampler/tpe.rs | 19 +++- rustuna_pyo3/src/trial_queue/mod.rs | 30 ++++++ rustuna_pyo3/src/trial_queue/to_python.rs | 38 ++++++++ .../tests/sampler_tests/test_cmaes.py | 4 +- .../storage_tests/test_journal_storage.py | 1 + .../storage_tests/test_to_rustuna_storage.py | 4 + rustuna_pyo3/tests/test_optuna_samplers.py | 5 + rustuna_pyo3/tests/test_rustuna.py | 6 +- rustuna_pyo3/tests/test_samplers.py | 11 +++ rustuna_sampler/src/nsgaii.rs | 3 + rustuna_sampler/src/qmc/sampler.rs | 7 +- rustuna_sampler/src/tpe/sampler.rs | 92 +++++++++++++++---- 22 files changed, 385 insertions(+), 65 deletions(-) create mode 100644 rustuna_pyo3/src/trial_queue/to_python.rs diff --git a/rustuna_core/src/sampler.rs b/rustuna_core/src/sampler.rs index 94237978..ff38b982 100644 --- a/rustuna_core/src/sampler.rs +++ b/rustuna_core/src/sampler.rs @@ -42,7 +42,12 @@ pub trait Sampler: Send + Sync { /// /// This corresponds to Optuna's `before_trial` hook. The trial can be retrieved from /// `storage` with `ctx.trial_id`, and the study can be retrieved with `ctx.study_id`. - fn before_trial(&self, _ctx: &Context, _storage: Arc>) -> Result<()> { + fn before_trial( + &self, + _ctx: &Context, + _storage: Arc>, + _trial_queue: Arc, + ) -> Result<()> { Ok(()) } @@ -55,6 +60,7 @@ pub trait Sampler: Send + Sync { &self, ctx: &Context, storage: Arc>, + trial_queue: Arc, name: &str, distribution: &Distribution, ) -> Result; @@ -71,6 +77,7 @@ pub trait Sampler: Send + Sync { &self, ctx: &Context, storage: Arc>, + trial_queue: Arc, search_space: &HashMap, ) -> Result>; /// Hook called when a trial is about to be finalized with the given state. @@ -81,6 +88,7 @@ pub trait Sampler: Send + Sync { &self, _ctx: &Context, _storage: Arc>, + _trial_queue: Arc, _state_values: &TrialStateValues, ) -> Result<()> { Ok(()) @@ -175,6 +183,7 @@ impl Sampler for RandomSampler { &self, _ctx: &Context, _storage: Arc>, + _trial_queue: Arc, _name: &str, distribution: &Distribution, ) -> Result { @@ -223,6 +232,7 @@ impl Sampler for RandomSampler { &self, _ctx: &Context, _storage: Arc>, + _trial_queue: Arc, _search_space: &HashMap, ) -> Result> { unreachable!() @@ -232,6 +242,7 @@ impl Sampler for RandomSampler { &self, _ctx: &Context, _storage: Arc>, + _trial_queue: Arc, _state_values: &TrialStateValues, ) -> Result<()> { Ok(()) @@ -246,6 +257,7 @@ mod tests { use crate::storage::InMemoryStorage; use crate::study::create_study; use crate::trial::Trial; + use crate::trial_queue::InMemoryTrialQueue; pub struct DummyJointSampler { joint_params: HashMap, @@ -255,6 +267,7 @@ mod tests { &self, _ctx: &Context, _storage: Arc>, + _trial_queue: Arc, _name: &str, _distribution: &Distribution, ) -> Result { @@ -269,6 +282,7 @@ mod tests { &self, _ctx: &Context, _storage: Arc>, + _trial_queue: Arc, _search_space: &HashMap, ) -> Result> { Ok(self.joint_params.clone()) @@ -278,6 +292,7 @@ mod tests { &self, _ctx: &Context, _storage: Arc>, + _trial_queue: Arc, _state_values: &TrialStateValues, ) -> Result<()> { Ok(()) @@ -294,12 +309,14 @@ mod tests { fn random_sampler_can_be_shared_between_threads() -> Result<()> { let sampler: Arc = Arc::new(RandomSampler::seed_from_u64(0)); let storage: Arc> = Arc::new(RwLock::new(InMemoryStorage::new())); + let trial_queue: Arc = Arc::new(InMemoryTrialQueue::new()); let distribution = Distribution::new_float(-1.0, 1.0, None, false); let mut handles = Vec::new(); for thread_id in 0..4 { let sampler = Arc::clone(&sampler); let storage = Arc::clone(&storage); + let trial_queue = Arc::clone(&trial_queue); let distribution = distribution.clone(); handles.push(thread::spawn(move || -> Result<()> { for trial_number in 0..100 { @@ -312,6 +329,7 @@ mod tests { let value = sampler.sample_independent( &ctx, Arc::clone(&storage), + Arc::clone(&trial_queue), "x", &distribution, )?; diff --git a/rustuna_core/src/study.rs b/rustuna_core/src/study.rs index 1e6bc661..4e4f76b9 100644 --- a/rustuna_core/src/study.rs +++ b/rustuna_core/src/study.rs @@ -183,7 +183,8 @@ impl Study { trial_id: persisted_trial.id, directions: self.directions.clone(), }; - self.sampler.before_trial(&ctx, self.storage.clone())?; + self.sampler + .before_trial(&ctx, self.storage.clone(), Arc::clone(&self.queue))?; let joint_params: HashMap = if self.sampler.support_joint_sampling() { @@ -198,9 +199,12 @@ impl Study { })? .get_joint_search_space(self.id)?; - let params = - self.sampler - .sample_joint(&ctx, self.storage.clone(), &joint_search_space)?; + let params = self.sampler.sample_joint( + &ctx, + self.storage.clone(), + Arc::clone(&self.queue), + &joint_search_space, + )?; let mut joint_params = HashMap::new(); for (name, param_value) in params { if !joint_search_space.contains_key(&name) { @@ -219,6 +223,7 @@ impl Study { self.directions.clone(), Arc::clone(&self.storage), Arc::clone(&self.sampler), + Arc::clone(&self.queue), joint_params, ); Ok(trial) @@ -254,9 +259,12 @@ impl Study { trial_number, trial_id, }; - let after_trial_result = - self.sampler - .after_trial(&ctx, self.storage.clone(), &state_values); + let after_trial_result = self.sampler.after_trial( + &ctx, + self.storage.clone(), + Arc::clone(&self.queue), + &state_values, + ); let mut storage_guard = self.storage.write().map_err(|e| { Error::with_reason( @@ -579,6 +587,7 @@ mod tests { &self, _ctx: &SamplerContext, _storage: Arc>, + _trial_queue: Arc, _name: &str, _distribution: &Distribution, ) -> Result { @@ -593,6 +602,7 @@ mod tests { &self, _ctx: &SamplerContext, _storage: Arc>, + _trial_queue: Arc, _search_space: &HashMap, ) -> Result> { unreachable!() @@ -602,6 +612,7 @@ mod tests { &self, ctx: &SamplerContext, storage: Arc>, + _trial_queue: Arc, state_values: &TrialStateValues, ) -> Result<()> { let mut storage_guard = storage.write().map_err(|e| { diff --git a/rustuna_core/src/trial.rs b/rustuna_core/src/trial.rs index b880ef05..1d1c7c03 100644 --- a/rustuna_core/src/trial.rs +++ b/rustuna_core/src/trial.rs @@ -9,6 +9,7 @@ use crate::distribution::Distribution; use crate::sampler::{Context as SamplerContext, Sampler}; use crate::storage::Storage; use crate::study::Direction; +use crate::trial_queue::TrialQueue; use crate::{Error, ErrorKind, Result}; const CONSTRAINTS_KEY: &str = "constraints"; @@ -27,6 +28,7 @@ pub struct Trial { directions: Vec, storage: Arc>, sampler: Arc, + trial_queue: Arc, joint_params: HashMap, fixed_params: HashMap, cached_user_attrs: HashMap, @@ -38,6 +40,7 @@ impl Trial { directions: Vec, storage: Arc>, sampler: Arc, + trial_queue: Arc, joint_params: HashMap, ) -> Self { let fixed_params = extract_fixed_params(&trial.attrs); @@ -58,6 +61,7 @@ impl Trial { directions, storage, sampler, + trial_queue, joint_params, fixed_params, cached_user_attrs, @@ -136,9 +140,13 @@ impl Trial { trial_id: self.id, directions: self.directions.clone(), }; - let param_value = - self.sampler - .sample_independent(&context, self.storage.clone(), name, distribution)?; + let param_value = self.sampler.sample_independent( + &context, + self.storage.clone(), + Arc::clone(&self.trial_queue), + name, + distribution, + )?; let mut storage_guard = self.storage.write().map_err(|e| { Error::with_reason( diff --git a/rustuna_pyo3/rustuna/_protocols.py b/rustuna_pyo3/rustuna/_protocols.py index 835325b3..4290f8e2 100644 --- a/rustuna_pyo3/rustuna/_protocols.py +++ b/rustuna_pyo3/rustuna/_protocols.py @@ -9,6 +9,7 @@ from rustuna.samplers import SamplerContext from rustuna.study import PersistedStudy, StudyDirection from rustuna.trial import PersistedTrial, TrialState + from rustuna.trial_queue import TrialQueueProtocol class SamplerProtocol(Protocol): @@ -26,6 +27,7 @@ def sample_joint( self, ctx: SamplerContext, storage: StorageProtocol, + trial_queue: TrialQueueProtocol, search_space: dict[str, Distribution], ) -> dict[str, float]: """Sample multiple parameters simultaneously. @@ -33,6 +35,7 @@ def sample_joint( Args: ctx: Sampler context. storage: Storage object. + trial_queue: Trial queue shared by this study. search_space: Parameter distributions. Returns: @@ -43,6 +46,7 @@ def before_trial( self, ctx: SamplerContext, storage: StorageProtocol, + trial_queue: TrialQueueProtocol, ) -> None: """Run sampler pre-processing before search-space inference. @@ -52,12 +56,14 @@ def before_trial( Args: ctx: Sampler context. storage: Storage object. + trial_queue: Trial queue shared by this study. """ def sample_independent( self, ctx: SamplerContext, storage: StorageProtocol, + trial_queue: TrialQueueProtocol, name: str, distribution: Distribution, ) -> float: @@ -66,6 +72,7 @@ def sample_independent( Args: ctx: Sampler context. storage: Storage object. + trial_queue: Trial queue shared by this study. name: Parameter name. distribution: Parameter distribution. @@ -77,6 +84,7 @@ def after_trial( self, ctx: SamplerContext, storage: StorageProtocol, + trial_queue: TrialQueueProtocol, state: TrialState, values: list[float] | None = None, ) -> None: @@ -85,6 +93,7 @@ def after_trial( Args: ctx: Sampler context. storage: Storage object. + trial_queue: Trial queue shared by this study. state: Final trial state. values: Final objective values. ``None`` unless the trial completed. """ diff --git a/rustuna_pyo3/rustuna/_rustuna.pyi b/rustuna_pyo3/rustuna/_rustuna.pyi index 1af6e861..dd1bec25 100644 --- a/rustuna_pyo3/rustuna/_rustuna.pyi +++ b/rustuna_pyo3/rustuna/_rustuna.pyi @@ -1165,6 +1165,7 @@ class SamplerContext: Attributes: study_id: Study ID. trial_number: Trial number. + trial_id: Trial ID. directions: Optimization directions. """ @@ -1199,12 +1200,14 @@ class RandomSampler: self, ctx: SamplerContext, storage: StorageProtocol, + trial_queue: TrialQueueProtocol, search_space: dict[str, Distribution], ) -> dict[str, float]: ... def sample_independent( self, ctx: SamplerContext, storage: StorageProtocol, + trial_queue: TrialQueueProtocol, name: str, distribution: Distribution, ) -> float: ... @@ -1212,11 +1215,13 @@ class RandomSampler: self, ctx: SamplerContext, storage: StorageProtocol, + trial_queue: TrialQueueProtocol, ) -> None: ... def after_trial( self, ctx: SamplerContext, storage: StorageProtocol, + trial_queue: TrialQueueProtocol, state: TrialState, values: list[float] | None = None, ) -> None: ... @@ -1299,12 +1304,14 @@ class TPESampler: self, ctx: SamplerContext, storage: StorageProtocol, + trial_queue: TrialQueueProtocol, search_space: dict[str, Distribution], ) -> dict[str, float]: ... def sample_independent( self, ctx: SamplerContext, storage: StorageProtocol, + trial_queue: TrialQueueProtocol, name: str, distribution: Distribution, ) -> float: ... @@ -1312,11 +1319,13 @@ class TPESampler: self, ctx: SamplerContext, storage: StorageProtocol, + trial_queue: TrialQueueProtocol, ) -> None: ... def after_trial( self, ctx: SamplerContext, storage: StorageProtocol, + trial_queue: TrialQueueProtocol, state: TrialState, values: list[float] | None = None, ) -> None: ... @@ -1386,12 +1395,14 @@ class NSGAIISampler: self, ctx: SamplerContext, storage: StorageProtocol, + trial_queue: TrialQueueProtocol, search_space: dict[str, Distribution], ) -> dict[str, float]: ... def sample_independent( self, ctx: SamplerContext, storage: StorageProtocol, + trial_queue: TrialQueueProtocol, name: str, distribution: Distribution, ) -> float: ... @@ -1399,11 +1410,13 @@ class NSGAIISampler: self, ctx: SamplerContext, storage: StorageProtocol, + trial_queue: TrialQueueProtocol, ) -> None: ... def after_trial( self, ctx: SamplerContext, storage: StorageProtocol, + trial_queue: TrialQueueProtocol, state: TrialState, values: list[float] | None = None, ) -> None: ... @@ -1434,12 +1447,14 @@ class CmaEsSampler: self, ctx: SamplerContext, storage: StorageProtocol, + trial_queue: TrialQueueProtocol, search_space: dict[str, Distribution], ) -> dict[str, float]: ... def sample_independent( self, ctx: SamplerContext, storage: StorageProtocol, + trial_queue: TrialQueueProtocol, name: str, distribution: Distribution, ) -> float: ... @@ -1447,11 +1462,13 @@ class CmaEsSampler: self, ctx: SamplerContext, storage: StorageProtocol, + trial_queue: TrialQueueProtocol, ) -> None: ... def after_trial( self, ctx: SamplerContext, storage: StorageProtocol, + trial_queue: TrialQueueProtocol, state: TrialState, values: list[float] | None = None, ) -> None: ... diff --git a/rustuna_pyo3/rustuna/converter/_sampler.py b/rustuna_pyo3/rustuna/converter/_sampler.py index b993dc5d..56ae16da 100644 --- a/rustuna_pyo3/rustuna/converter/_sampler.py +++ b/rustuna_pyo3/rustuna/converter/_sampler.py @@ -19,6 +19,7 @@ ) from rustuna.converter._storage import ToRustunaStorage from rustuna.converter._trial import to_rustuna_state +from rustuna.trial_queue import InMemoryTrialQueue, TrialQueueProtocol if TYPE_CHECKING: from rustuna.samplers import SamplerProtocol @@ -53,12 +54,18 @@ def __init__(self, sampler: SamplerProtocol) -> None: self._sampler = sampler self._inter_section_search_space = IntersectionSearchSpace() self._storage: ToRustStorage | None = None + self._trial_queues: dict[int, TrialQueueProtocol] = {} def _get_storage(self, storage: BaseStorage) -> StorageProtocol: if self._storage is None: self._storage = ToRustStorage(ToRustunaStorage(storage)) return self._storage + def _get_trial_queue(self, study_id: int) -> TrialQueueProtocol: + if study_id not in self._trial_queues: + self._trial_queues[study_id] = InMemoryTrialQueue() + return self._trial_queues[study_id] + def sample_relative( self, study: Study, @@ -76,6 +83,7 @@ def sample_relative( directions=to_rustuna_directions(study._directions), ) storage = self._get_storage(study._storage) + trial_queue = self._get_trial_queue(study._study_id) # PyObjectStorage syncs its Rustuna-side cache with the underlying Optuna storage # only when get_trials() is called. In this flow, trials are created and completed # through the Optuna storage directly, so sync explicitly here; otherwise Rustuna @@ -84,7 +92,9 @@ def sample_relative( # TODO(c-bata): Consider how to remove this redundant storage.get_trials() call. storage.get_trials(study._study_id, states=[rustuna.trial.TrialState.COMPLETE]) rustuna_search_space = to_rustuna_distributions(search_space) - internal_params = self._sampler.sample_joint(ctx, storage, rustuna_search_space) + internal_params = self._sampler.sample_joint( + ctx, storage, trial_queue, rustuna_search_space + ) external_params: dict[str, Any] = {} for param_name in internal_params: distribution = search_space[param_name] @@ -103,7 +113,8 @@ def before_trial(self, study: Study, trial: FrozenTrial) -> None: directions=to_rustuna_directions(study._directions), ) storage = self._get_storage(study._storage) - self._sampler.before_trial(ctx, storage) + trial_queue = self._get_trial_queue(study._study_id) + self._sampler.before_trial(ctx, storage, trial_queue) def sample_independent( self, @@ -120,9 +131,10 @@ def sample_independent( directions=to_rustuna_directions(study._directions), ) storage = self._get_storage(study._storage) + trial_queue = self._get_trial_queue(study._study_id) distribution = to_rustuna_distribution(param_distribution) internal_param = self._sampler.sample_independent( - ctx, storage, param_name, distribution + ctx, storage, trial_queue, param_name, distribution ) return param_distribution.to_external_repr(internal_param) @@ -162,9 +174,11 @@ def after_trial( directions=to_rustuna_directions(study._directions), ) storage = self._get_storage(study._storage) + trial_queue = self._get_trial_queue(study._study_id) self._sampler.after_trial( ctx, storage, + trial_queue, to_rustuna_state(state), list(values) if values is not None else None, ) diff --git a/rustuna_pyo3/src/sampler/cmaes.rs b/rustuna_pyo3/src/sampler/cmaes.rs index c5a6d9e9..feb919a8 100644 --- a/rustuna_pyo3/src/sampler/cmaes.rs +++ b/rustuna_pyo3/src/sampler/cmaes.rs @@ -17,6 +17,7 @@ use super::{extract_storage, PySamplerContext}; use crate::distribution::PyDistribution; use crate::exception::err_to_exceptions; use crate::trial::PyTrialState; +use crate::trial_queue::extract_trial_queue; /// A CMA-ES sampler backed by Python's `cmaes` package. /// @@ -229,11 +230,12 @@ impl Sampler for CmaEsSampler { &self, ctx: &Context, storage: Arc>, + trial_queue: Arc, name: &str, distribution: &Distribution, ) -> Result { self.random_sampler - .sample_independent(ctx, storage, name, distribution) + .sample_independent(ctx, storage, trial_queue, name, distribution) } fn support_joint_sampling(&self) -> bool { @@ -244,6 +246,7 @@ impl Sampler for CmaEsSampler { &self, ctx: &Context, storage: Arc>, + _trial_queue: Arc, search_space: &HashMap, ) -> Result> { self.state @@ -294,16 +297,18 @@ impl PyCmaEsSampler { py: Python<'_>, ctx: &PySamplerContext, storage: Py, + trial_queue: Py, name: &str, distribution: &PyDistribution, ) -> PyResult { let arc_storage = extract_storage(storage)?; + let arc_trial_queue = extract_trial_queue(trial_queue)?; let context = ctx.context.clone(); let name = name.to_owned(); let distribution = distribution.distribution.clone(); py.detach(|| { self.sampler - .sample_independent(&context, arc_storage, &name, &distribution) + .sample_independent(&context, arc_storage, arc_trial_queue, &name, &distribution) .map_err(|e| { PyRuntimeError::new_err(format!("Failed to sample independent: {e:?}")) }) @@ -315,9 +320,11 @@ impl PyCmaEsSampler { py: Python<'_>, ctx: &PySamplerContext, storage: Py, + trial_queue: Py, search_space: HashMap, ) -> PyResult> { let arc_storage = extract_storage(storage)?; + let arc_trial_queue = extract_trial_queue(trial_queue)?; let context = ctx.context.clone(); let search_space = search_space .into_iter() @@ -325,26 +332,33 @@ impl PyCmaEsSampler { .collect(); py.detach(|| { self.sampler - .sample_joint(&context, arc_storage, &search_space) + .sample_joint(&context, arc_storage, arc_trial_queue, &search_space) .map_err(err_to_exceptions) }) } - fn before_trial(&self, ctx: &PySamplerContext, storage: Py) -> PyResult<()> { - let _ = (ctx, storage); + fn before_trial( + &self, + ctx: &PySamplerContext, + storage: Py, + trial_queue: Py, + ) -> PyResult<()> { + let _ = (ctx, storage, trial_queue); Ok(()) } - #[pyo3(signature = (ctx, storage, state, values = None))] + #[pyo3(signature = (ctx, storage, trial_queue, state, values = None))] fn after_trial( &self, py: Python<'_>, ctx: &PySamplerContext, storage: Py, + trial_queue: Py, state: PyTrialState, values: Option>, ) -> PyResult<()> { let arc_storage = extract_storage(storage)?; + let arc_trial_queue = extract_trial_queue(trial_queue)?; let state_values = match state { PyTrialState::RUNNING => TrialStateValues::Running, PyTrialState::COMPLETE => TrialStateValues::Complete(values.ok_or( @@ -357,7 +371,7 @@ impl PyCmaEsSampler { let context = ctx.context.clone(); py.detach(|| { self.sampler - .after_trial(&context, arc_storage, &state_values) + .after_trial(&context, arc_storage, arc_trial_queue, &state_values) .map_err(|e| PyRuntimeError::new_err(format!("Failed to call after_trial: {e:?}"))) }) } diff --git a/rustuna_pyo3/src/sampler/nsgaii.rs b/rustuna_pyo3/src/sampler/nsgaii.rs index 9369c0df..64ae084b 100644 --- a/rustuna_pyo3/src/sampler/nsgaii.rs +++ b/rustuna_pyo3/src/sampler/nsgaii.rs @@ -12,6 +12,7 @@ use rustuna_sampler::nsgaii::{NsgaiiBuilder, NsgaiiSampler}; use crate::distribution::PyDistribution; use crate::sampler::{extract_storage, PySamplerContext}; use crate::trial::PyTrialState; +use crate::trial_queue::extract_trial_queue; #[derive(Clone)] #[pyclass(name = "NSGAIISampler", from_py_object)] @@ -56,16 +57,18 @@ impl PyNsgaiiSampler { py: Python<'_>, ctx: &PySamplerContext, storage: Py, + trial_queue: Py, name: &str, distribution: &PyDistribution, ) -> PyResult { let arc_storage = extract_storage(storage)?; + let arc_trial_queue = extract_trial_queue(trial_queue)?; let context = ctx.context.clone(); let name = name.to_owned(); let distribution = distribution.distribution.clone(); py.detach(|| { self.sampler - .sample_independent(&context, arc_storage, &name, &distribution) + .sample_independent(&context, arc_storage, arc_trial_queue, &name, &distribution) .map_err(|e| { PyRuntimeError::new_err(format!("Failed to sample independent: {e:?}")) }) @@ -77,9 +80,11 @@ impl PyNsgaiiSampler { py: Python<'_>, ctx: &PySamplerContext, storage: Py, + trial_queue: Py, search_space: HashMap, ) -> PyResult> { let arc_storage = extract_storage(storage)?; + let arc_trial_queue = extract_trial_queue(trial_queue)?; let context = ctx.context.clone(); let search_space = search_space .into_iter() @@ -87,26 +92,33 @@ impl PyNsgaiiSampler { .collect(); py.detach(|| { self.sampler - .sample_joint(&context, arc_storage, &search_space) + .sample_joint(&context, arc_storage, arc_trial_queue, &search_space) .map_err(|e| PyRuntimeError::new_err(format!("Failed to sample joint: {e:?}"))) }) } - fn before_trial(&self, ctx: &PySamplerContext, storage: Py) -> PyResult<()> { - let _ = (ctx, storage); + fn before_trial( + &self, + ctx: &PySamplerContext, + storage: Py, + trial_queue: Py, + ) -> PyResult<()> { + let _ = (ctx, storage, trial_queue); Ok(()) } - #[pyo3(signature = (ctx, storage, state, values = None))] + #[pyo3(signature = (ctx, storage, trial_queue, state, values = None))] fn after_trial( &self, py: Python<'_>, ctx: &PySamplerContext, storage: Py, + trial_queue: Py, state: PyTrialState, values: Option>, ) -> PyResult<()> { let arc_storage = extract_storage(storage)?; + let arc_trial_queue = extract_trial_queue(trial_queue)?; let state_values = match state { PyTrialState::RUNNING => TrialStateValues::Running, PyTrialState::COMPLETE => TrialStateValues::Complete(values.ok_or( @@ -119,7 +131,7 @@ impl PyNsgaiiSampler { let context = ctx.context.clone(); py.detach(|| { self.sampler - .after_trial(&context, arc_storage, &state_values) + .after_trial(&context, arc_storage, arc_trial_queue, &state_values) .map_err(|e| PyRuntimeError::new_err(format!("Failed to call after_trial: {e:?}"))) }) } diff --git a/rustuna_pyo3/src/sampler/random.rs b/rustuna_pyo3/src/sampler/random.rs index 78ceba84..5051cf52 100644 --- a/rustuna_pyo3/src/sampler/random.rs +++ b/rustuna_pyo3/src/sampler/random.rs @@ -9,6 +9,7 @@ use rustuna_core::sampler::{RandomSampler, Sampler}; use crate::distribution::PyDistribution; use crate::sampler::{extract_storage, PySamplerContext}; use crate::trial::PyTrialState; +use crate::trial_queue::extract_trial_queue; #[derive(Clone)] #[pyclass(name = "RandomSampler", from_py_object)] @@ -40,16 +41,18 @@ impl PyRandomSampler { py: Python<'_>, ctx: &PySamplerContext, storage: Py, + trial_queue: Py, name: &str, distribution: &PyDistribution, ) -> PyResult { let arc_storage = extract_storage(storage)?; + let arc_trial_queue = extract_trial_queue(trial_queue)?; let context = ctx.context.clone(); let name = name.to_owned(); let distribution = distribution.distribution.clone(); py.detach(|| { self.sampler - .sample_independent(&context, arc_storage, &name, &distribution) + .sample_independent(&context, arc_storage, arc_trial_queue, &name, &distribution) .map_err(|e| { PyRuntimeError::new_err(format!("Failed to sample independent: {e:?}")) }) @@ -60,26 +63,33 @@ impl PyRandomSampler { &self, ctx: &PySamplerContext, storage: Py, + trial_queue: Py, search_space: HashMap, ) -> PyResult> { - let _ = (ctx, storage, search_space); + let _ = (ctx, storage, trial_queue, search_space); Ok(HashMap::new()) } - fn before_trial(&self, ctx: &PySamplerContext, storage: Py) -> PyResult<()> { - let _ = (ctx, storage); + fn before_trial( + &self, + ctx: &PySamplerContext, + storage: Py, + trial_queue: Py, + ) -> PyResult<()> { + let _ = (ctx, storage, trial_queue); Ok(()) } - #[pyo3(signature = (ctx, storage, state, values = None))] + #[pyo3(signature = (ctx, storage, trial_queue, state, values = None))] fn after_trial( &self, ctx: &PySamplerContext, storage: Py, + trial_queue: Py, state: PyTrialState, values: Option>, ) -> PyResult<()> { - let _ = (ctx, storage, state, values); + let _ = (ctx, storage, trial_queue, state, values); Ok(()) } } diff --git a/rustuna_pyo3/src/sampler/to_rust.rs b/rustuna_pyo3/src/sampler/to_rust.rs index 5f98c4bb..73775f90 100644 --- a/rustuna_pyo3/src/sampler/to_rust.rs +++ b/rustuna_pyo3/src/sampler/to_rust.rs @@ -13,6 +13,7 @@ use crate::distribution::PyDistribution; use crate::sampler::PySamplerContext; use crate::storage::to_python::ToPythonStorage; use crate::trial::PyTrialState; +use crate::trial_queue::to_python::ToPythonTrialQueue; // ToRustSampler adapts a Python object implementing rustuna.SamplerProtocol to // rustuna_core::sampler::Sampler. Rustuna can therefore use Python samplers through the same @@ -32,6 +33,7 @@ impl Sampler for ToRustSampler { &self, ctx: &SamplerContext, storage: Arc>, + trial_queue: Arc, ) -> rustuna_core::Result<()> { let obj = self.obj.lock().map_err(|e| { rustuna_core::Error::with_reason( @@ -42,7 +44,14 @@ impl Sampler for ToRustSampler { Python::attach(|py| { let py_ctx = PySamplerContext::from(ctx.clone()); let py_storage = ToPythonStorage::new(storage); - obj.call_method1(py, "before_trial", (py_ctx, py_storage)) + let py_trial_queue = + Py::new(py, ToPythonTrialQueue::new(trial_queue)).map_err(|e| { + rustuna_core::Error::with_reason( + rustuna_core::ErrorKind::SamplerError, + e.to_string(), + ) + })?; + obj.call_method1(py, "before_trial", (py_ctx, py_storage, py_trial_queue)) .map_err(|e| { rustuna_core::Error::with_reason( rustuna_core::ErrorKind::SamplerError, @@ -57,6 +66,7 @@ impl Sampler for ToRustSampler { &self, ctx: &SamplerContext, storage: Arc>, + trial_queue: Arc, name: &str, distribution: &rustuna_core::distribution::Distribution, ) -> rustuna_core::Result { @@ -79,12 +89,19 @@ impl Sampler for ToRustSampler { Python::attach(|py| { let py_ctx = PySamplerContext::from(ctx.clone()); let py_storage = ToPythonStorage::new(storage.clone()); + let py_trial_queue = + Py::new(py, ToPythonTrialQueue::new(trial_queue)).map_err(|e| { + rustuna_core::Error::with_reason( + rustuna_core::ErrorKind::SamplerError, + e.to_string(), + ) + })?; let py_distribution = PyDistribution::new(distribution.clone(), name, &study_attrs); let py_result = obj .call_method1( py, "sample_independent", - (py_ctx, py_storage, name, py_distribution), + (py_ctx, py_storage, py_trial_queue, name, py_distribution), ) .map_err(|e| { rustuna_core::Error::with_reason( @@ -118,6 +135,7 @@ impl Sampler for ToRustSampler { &self, ctx: &SamplerContext, storage: Arc>, + trial_queue: Arc, search_space: &HashMap, ) -> rustuna_core::Result> { let mut guard = storage.write().map_err(|e| { @@ -136,6 +154,13 @@ impl Sampler for ToRustSampler { Python::attach(|py| { let py_ctx = PySamplerContext::from(ctx.clone()); let py_storage = ToPythonStorage::new(storage.clone()); + let py_trial_queue = + Py::new(py, ToPythonTrialQueue::new(trial_queue)).map_err(|e| { + rustuna_core::Error::with_reason( + rustuna_core::ErrorKind::SamplerError, + e.to_string(), + ) + })?; let py_search_space = PyDict::new(py); for (k, v) in search_space { let py_distribution = Py::new(py, PyDistribution::new(v.clone(), k, &study_attrs)) @@ -153,7 +178,11 @@ impl Sampler for ToRustSampler { })?; } let py_result = obj - .call_method1(py, "sample_joint", (py_ctx, py_storage, py_search_space)) + .call_method1( + py, + "sample_joint", + (py_ctx, py_storage, py_trial_queue, py_search_space), + ) .map_err(|e| { rustuna_core::Error::with_reason( rustuna_core::ErrorKind::SamplerError, @@ -174,6 +203,7 @@ impl Sampler for ToRustSampler { &self, ctx: &SamplerContext, storage: Arc>, + trial_queue: Arc, state_values: &TrialStateValues, ) -> rustuna_core::Result<()> { let py_state = PyTrialState::from(state_values.clone()); @@ -191,13 +221,24 @@ impl Sampler for ToRustSampler { Python::attach(|py| { let py_ctx = PySamplerContext::from(ctx.clone()); let py_storage = ToPythonStorage::new(storage.clone()); - obj.call_method1(py, "after_trial", (py_ctx, py_storage, py_state, py_values)) - .map_err(|e| { + let py_trial_queue = + Py::new(py, ToPythonTrialQueue::new(trial_queue)).map_err(|e| { rustuna_core::Error::with_reason( rustuna_core::ErrorKind::SamplerError, e.to_string(), ) })?; + obj.call_method1( + py, + "after_trial", + (py_ctx, py_storage, py_trial_queue, py_state, py_values), + ) + .map_err(|e| { + rustuna_core::Error::with_reason( + rustuna_core::ErrorKind::SamplerError, + e.to_string(), + ) + })?; Ok(()) }) } diff --git a/rustuna_pyo3/src/sampler/tpe.rs b/rustuna_pyo3/src/sampler/tpe.rs index ca299eda..74b9e4c1 100644 --- a/rustuna_pyo3/src/sampler/tpe.rs +++ b/rustuna_pyo3/src/sampler/tpe.rs @@ -12,6 +12,7 @@ use rustuna_sampler::tpe::{TpeBuilder, TpeSampler}; use crate::distribution::PyDistribution; use crate::sampler::{extract_storage, PySamplerContext}; use crate::trial::PyTrialState; +use crate::trial_queue::extract_trial_queue; #[derive(Clone)] #[pyclass(name = "TPESampler", from_py_object)] @@ -51,16 +52,18 @@ impl PyTpeSampler { py: Python<'_>, ctx: &PySamplerContext, storage: Py, + trial_queue: Py, name: &str, distribution: &PyDistribution, ) -> PyResult { let arc_storage = extract_storage(storage)?; + let arc_trial_queue = extract_trial_queue(trial_queue)?; let context = ctx.context.clone(); let name = name.to_owned(); let distribution = distribution.distribution.clone(); py.detach(|| { self.sampler - .sample_independent(&context, arc_storage, &name, &distribution) + .sample_independent(&context, arc_storage, arc_trial_queue, &name, &distribution) .map_err(|e| { PyRuntimeError::new_err(format!("Failed to sample independent: {e:?}")) }) @@ -72,9 +75,11 @@ impl PyTpeSampler { py: Python<'_>, ctx: &PySamplerContext, storage: Py, + trial_queue: Py, search_space: HashMap, ) -> PyResult> { let arc_storage = extract_storage(storage)?; + let arc_trial_queue = extract_trial_queue(trial_queue)?; let context = ctx.context.clone(); let search_space = search_space .into_iter() @@ -82,7 +87,7 @@ impl PyTpeSampler { .collect(); py.detach(|| { self.sampler - .sample_joint(&context, arc_storage, &search_space) + .sample_joint(&context, arc_storage, arc_trial_queue, &search_space) .map_err(|e| PyRuntimeError::new_err(format!("Failed to sample joint: {e:?}"))) }) } @@ -92,26 +97,30 @@ impl PyTpeSampler { py: Python<'_>, ctx: &PySamplerContext, storage: Py, + trial_queue: Py, ) -> PyResult<()> { let arc_storage = extract_storage(storage)?; + let arc_trial_queue = extract_trial_queue(trial_queue)?; let context = ctx.context.clone(); py.detach(|| { self.sampler - .before_trial(&context, arc_storage) + .before_trial(&context, arc_storage, arc_trial_queue) .map_err(|e| PyRuntimeError::new_err(format!("Failed to call before_trial: {e:?}"))) }) } - #[pyo3(signature = (ctx, storage, state, values = None))] + #[pyo3(signature = (ctx, storage, trial_queue, state, values = None))] fn after_trial( &self, py: Python<'_>, ctx: &PySamplerContext, storage: Py, + trial_queue: Py, state: PyTrialState, values: Option>, ) -> PyResult<()> { let arc_storage = extract_storage(storage)?; + let arc_trial_queue = extract_trial_queue(trial_queue)?; let state_values = match state { PyTrialState::RUNNING => TrialStateValues::Running, PyTrialState::COMPLETE => TrialStateValues::Complete(values.ok_or( @@ -124,7 +133,7 @@ impl PyTpeSampler { let context = ctx.context.clone(); py.detach(|| { self.sampler - .after_trial(&context, arc_storage, &state_values) + .after_trial(&context, arc_storage, arc_trial_queue, &state_values) .map_err(|e| PyRuntimeError::new_err(format!("Failed to call after_trial: {e:?}"))) }) } diff --git a/rustuna_pyo3/src/trial_queue/mod.rs b/rustuna_pyo3/src/trial_queue/mod.rs index 4fb9c11b..706331ca 100644 --- a/rustuna_pyo3/src/trial_queue/mod.rs +++ b/rustuna_pyo3/src/trial_queue/mod.rs @@ -1,4 +1,34 @@ +use std::sync::Arc; + +use pyo3::prelude::*; + +use rustuna_core::trial_queue::TrialQueue; + +use self::directory::PyDirectoryTrialQueue; +use self::inmemory::PyInMemoryTrialQueue; +use self::sqlite3::PySQLite3TrialQueue; +use self::to_python::ToPythonTrialQueue; +use self::to_rust::ToRustTrialQueue; + pub mod directory; pub mod inmemory; pub mod sqlite3; +pub(crate) mod to_python; pub mod to_rust; + +pub(crate) fn extract_trial_queue(trial_queue: Py) -> PyResult> { + Python::attach(|py| { + let trial_queue_ref = trial_queue.bind(py); + if let Ok(queue) = trial_queue_ref.extract::() { + Ok(queue.queue.clone() as Arc) + } else if let Ok(queue) = trial_queue_ref.extract::() { + Ok(queue.queue.clone() as Arc) + } else if let Ok(queue) = trial_queue_ref.extract::() { + Ok(queue.queue.clone() as Arc) + } else if let Ok(queue) = trial_queue_ref.extract::() { + Ok(queue.queue()) + } else { + Ok(Arc::new(ToRustTrialQueue::new(trial_queue)) as Arc) + } + }) +} diff --git a/rustuna_pyo3/src/trial_queue/to_python.rs b/rustuna_pyo3/src/trial_queue/to_python.rs new file mode 100644 index 00000000..69ed6755 --- /dev/null +++ b/rustuna_pyo3/src/trial_queue/to_python.rs @@ -0,0 +1,38 @@ +use std::sync::Arc; + +use pyo3::prelude::*; +use rustuna_core::trial_queue::TrialQueue; +use rustuna_core::ErrorKind; + +use crate::exception::err_to_exceptions; + +#[derive(Clone)] +#[pyclass(name = "ToPythonTrialQueue", module = "rustuna", from_py_object)] +pub(crate) struct ToPythonTrialQueue { + queue: Arc, +} + +impl ToPythonTrialQueue { + pub(crate) fn new(queue: Arc) -> Self { + Self { queue } + } + + pub(crate) fn queue(&self) -> Arc { + Arc::clone(&self.queue) + } +} + +#[pymethods] +impl ToPythonTrialQueue { + fn enqueue(&self, py: Python<'_>, trial_id: u32) -> PyResult<()> { + py.detach(|| self.queue.enqueue(trial_id).map_err(err_to_exceptions)) + } + + fn dequeue(&self, py: Python<'_>) -> PyResult> { + py.detach(|| match self.queue.dequeue() { + Ok(trial_id) => Ok(Some(trial_id)), + Err(error) if matches!(error.kind, ErrorKind::TrialQueueEmpty) => Ok(None), + Err(error) => Err(err_to_exceptions(error)), + }) + } +} diff --git a/rustuna_pyo3/tests/sampler_tests/test_cmaes.py b/rustuna_pyo3/tests/sampler_tests/test_cmaes.py index 41de9a15..19c26acb 100644 --- a/rustuna_pyo3/tests/sampler_tests/test_cmaes.py +++ b/rustuna_pyo3/tests/sampler_tests/test_cmaes.py @@ -37,7 +37,9 @@ def test_cmaes_sampler_samples_independently_from_multiple_threads() -> None: distribution = rustuna.distributions.FloatDistribution(-1, 1) def sample(_: int) -> float: - return sampler.sample_independent(ctx, storage, "x", distribution) + return sampler.sample_independent( + ctx, storage, study.trial_queue, "x", distribution + ) with ThreadPoolExecutor(max_workers=4) as executor: values = list(executor.map(sample, range(100))) diff --git a/rustuna_pyo3/tests/storage_tests/test_journal_storage.py b/rustuna_pyo3/tests/storage_tests/test_journal_storage.py index dec0d446..c8e8adb3 100644 --- a/rustuna_pyo3/tests/storage_tests/test_journal_storage.py +++ b/rustuna_pyo3/tests/storage_tests/test_journal_storage.py @@ -27,6 +27,7 @@ def test_journal_file_storage_can_be_used_by_native_sampler() -> None: value = rustuna.samplers.RandomSampler(seed=1).sample_independent( ctx, storage, + study.trial_queue, "x", rustuna.distributions.FloatDistribution(0, 1), ) diff --git a/rustuna_pyo3/tests/storage_tests/test_to_rustuna_storage.py b/rustuna_pyo3/tests/storage_tests/test_to_rustuna_storage.py index 12ab76a1..9b21a375 100644 --- a/rustuna_pyo3/tests/storage_tests/test_to_rustuna_storage.py +++ b/rustuna_pyo3/tests/storage_tests/test_to_rustuna_storage.py @@ -144,6 +144,7 @@ def before_trial( self, ctx: rustuna.samplers.SamplerContext, storage: rustuna.storages.StorageProtocol, + trial_queue: rustuna.trial_queue.TrialQueueProtocol, ) -> None: return None @@ -151,6 +152,7 @@ def sample_joint( self, ctx: rustuna.samplers.SamplerContext, storage: rustuna.storages.StorageProtocol, + trial_queue: rustuna.trial_queue.TrialQueueProtocol, search_space: dict[str, Distribution], ) -> dict[str, float]: # TODO(c-bata): Avoid calling sample_joint if the search space is empty. @@ -175,6 +177,7 @@ def sample_independent( self, ctx: rustuna.samplers.SamplerContext, storage: rustuna.storages.StorageProtocol, + trial_queue: rustuna.trial_queue.TrialQueueProtocol, name: str, distribution: Distribution, ) -> float: @@ -191,6 +194,7 @@ def after_trial( self, ctx: rustuna.samplers.SamplerContext, storage: rustuna.storages.StorageProtocol, + trial_queue: rustuna.trial_queue.TrialQueueProtocol, state: rustuna.trial.TrialState, values: list[float] | None = None, ) -> None: diff --git a/rustuna_pyo3/tests/test_optuna_samplers.py b/rustuna_pyo3/tests/test_optuna_samplers.py index cbe90ac0..4f2ada9c 100644 --- a/rustuna_pyo3/tests/test_optuna_samplers.py +++ b/rustuna_pyo3/tests/test_optuna_samplers.py @@ -72,6 +72,7 @@ def before_trial( self, ctx: rustuna.samplers.SamplerContext, storage: rustuna.storages.StorageProtocol, + trial_queue: rustuna.trial_queue.TrialQueueProtocol, ) -> None: self.before_trial_calls.append((ctx.study_id, ctx.trial_number)) @@ -79,6 +80,7 @@ def sample_joint( self, ctx: rustuna.samplers.SamplerContext, storage: rustuna.storages.StorageProtocol, + trial_queue: rustuna.trial_queue.TrialQueueProtocol, search_space: dict[str, Distribution], ) -> dict[str, float]: raise AssertionError("sample_joint must not be called") @@ -87,6 +89,7 @@ def sample_independent( self, ctx: rustuna.samplers.SamplerContext, storage: rustuna.storages.StorageProtocol, + trial_queue: rustuna.trial_queue.TrialQueueProtocol, name: str, distribution: Distribution, ) -> float: @@ -103,6 +106,7 @@ def after_trial( self, ctx: rustuna.samplers.SamplerContext, storage: rustuna.storages.StorageProtocol, + trial_queue: rustuna.trial_queue.TrialQueueProtocol, state: rustuna.trial.TrialState, values: Sequence[float] | None = None, ) -> None: @@ -121,6 +125,7 @@ def after_trial( self, ctx: rustuna.samplers.SamplerContext, storage: rustuna.storages.StorageProtocol, + trial_queue: rustuna.trial_queue.TrialQueueProtocol, state: rustuna.trial.TrialState, values: Sequence[float] | None = None, ) -> None: diff --git a/rustuna_pyo3/tests/test_rustuna.py b/rustuna_pyo3/tests/test_rustuna.py index 522a2e7c..e2cea9a1 100644 --- a/rustuna_pyo3/tests/test_rustuna.py +++ b/rustuna_pyo3/tests/test_rustuna.py @@ -407,7 +407,11 @@ def test_sample(): directions=study.directions, ) value = sampler.sample_independent( - ctx, storage, "x", rustuna.distributions.FloatDistribution(0, 1) + ctx, + storage, + study.trial_queue, + "x", + rustuna.distributions.FloatDistribution(0, 1), ) assert 0 <= value <= 1 diff --git a/rustuna_pyo3/tests/test_samplers.py b/rustuna_pyo3/tests/test_samplers.py index e3c8d097..6471fef2 100644 --- a/rustuna_pyo3/tests/test_samplers.py +++ b/rustuna_pyo3/tests/test_samplers.py @@ -22,6 +22,7 @@ def before_trial( self, ctx: rustuna.samplers.SamplerContext, storage: rustuna.storages.StorageProtocol, + trial_queue: rustuna.trial_queue.TrialQueueProtocol, ) -> None: return None @@ -29,6 +30,7 @@ def sample_joint( self, ctx: rustuna.samplers.SamplerContext, storage: rustuna.storages.StorageProtocol, + trial_queue: rustuna.trial_queue.TrialQueueProtocol, search_space: dict[str, Distribution], ) -> dict[str, float]: assert False, "Unreachable code" @@ -37,6 +39,7 @@ def sample_independent( self, ctx: rustuna.samplers.SamplerContext, storage: rustuna.storages.StorageProtocol, + trial_queue: rustuna.trial_queue.TrialQueueProtocol, name: str, distribution: Distribution, ) -> float: @@ -53,6 +56,7 @@ def after_trial( self, ctx: rustuna.samplers.SamplerContext, storage: rustuna.storages.StorageProtocol, + trial_queue: rustuna.trial_queue.TrialQueueProtocol, state: rustuna.trial.TrialState, values: list[float] | None = None, ) -> None: @@ -71,6 +75,7 @@ def before_trial( self, ctx: rustuna.samplers.SamplerContext, storage: rustuna.storages.StorageProtocol, + trial_queue: rustuna.trial_queue.TrialQueueProtocol, ) -> None: return None @@ -78,6 +83,7 @@ def sample_joint( self, ctx: rustuna.samplers.SamplerContext, storage: rustuna.storages.StorageProtocol, + trial_queue: rustuna.trial_queue.TrialQueueProtocol, search_space: dict[str, Distribution], ) -> dict[str, float]: params = {} @@ -97,6 +103,7 @@ def sample_independent( self, ctx: rustuna.samplers.SamplerContext, storage: rustuna.storages.StorageProtocol, + trial_queue: rustuna.trial_queue.TrialQueueProtocol, name: str, distribution: Distribution, ) -> float: @@ -113,6 +120,7 @@ def after_trial( self, ctx: rustuna.samplers.SamplerContext, storage: rustuna.storages.StorageProtocol, + trial_queue: rustuna.trial_queue.TrialQueueProtocol, state: rustuna.trial.TrialState, values: list[float] | None = None, ) -> None: @@ -130,6 +138,7 @@ def before_trial( self, ctx: rustuna.samplers.SamplerContext, storage: rustuna.storages.StorageProtocol, + trial_queue: rustuna.trial_queue.TrialQueueProtocol, ) -> None: trial = storage.get_trial(ctx.trial_id) self.before_trial_calls.append((ctx.study_id, ctx.trial_number, trial.state)) @@ -138,6 +147,7 @@ def after_trial( self, ctx: rustuna.samplers.SamplerContext, storage: rustuna.storages.StorageProtocol, + trial_queue: rustuna.trial_queue.TrialQueueProtocol, state: rustuna.trial.TrialState, values: list[float] | None = None, ) -> None: @@ -149,6 +159,7 @@ def after_trial( self, ctx: rustuna.samplers.SamplerContext, storage: rustuna.storages.StorageProtocol, + trial_queue: rustuna.trial_queue.TrialQueueProtocol, state: rustuna.trial.TrialState, values: list[float] | None = None, ) -> None: diff --git a/rustuna_sampler/src/nsgaii.rs b/rustuna_sampler/src/nsgaii.rs index 41923e02..169c7be3 100644 --- a/rustuna_sampler/src/nsgaii.rs +++ b/rustuna_sampler/src/nsgaii.rs @@ -414,6 +414,7 @@ impl Sampler for NsgaiiSampler { &self, _ctx: &Context, _storage: Arc>, + _trial_queue: Arc, _name: &str, distribution: &Distribution, ) -> Result { @@ -493,6 +494,7 @@ impl Sampler for NsgaiiSampler { &self, ctx: &Context, storage: Arc>, + _trial_queue: Arc, search_space: &HashMap, ) -> Result> { let mut guard = storage @@ -634,6 +636,7 @@ impl Sampler for NsgaiiSampler { &self, ctx: &Context, storage: Arc>, + _trial_queue: Arc, state_values: &TrialStateValues, ) -> Result<()> { if let TrialStateValues::Complete(_) = state_values { diff --git a/rustuna_sampler/src/qmc/sampler.rs b/rustuna_sampler/src/qmc/sampler.rs index a4e0d040..924dd154 100644 --- a/rustuna_sampler/src/qmc/sampler.rs +++ b/rustuna_sampler/src/qmc/sampler.rs @@ -89,11 +89,12 @@ impl Sampler for QmcSampler { &self, ctx: &Context, storage: Arc>, + trial_queue: Arc, name: &str, distribution: &Distribution, ) -> Result { self.independent_sampler - .sample_independent(ctx, storage, name, distribution) + .sample_independent(ctx, storage, trial_queue, name, distribution) } fn support_joint_sampling(&self) -> bool { @@ -104,6 +105,7 @@ impl Sampler for QmcSampler { &self, ctx: &Context, storage: Arc>, + _trial_queue: Arc, search_space: &HashMap, ) -> Result> { if search_space.is_empty() { @@ -148,10 +150,11 @@ impl Sampler for QmcSampler { &self, ctx: &Context, storage: Arc>, + trial_queue: Arc, state_values: &TrialStateValues, ) -> Result<()> { self.independent_sampler - .after_trial(ctx, storage, state_values) + .after_trial(ctx, storage, trial_queue, state_values) } } diff --git a/rustuna_sampler/src/tpe/sampler.rs b/rustuna_sampler/src/tpe/sampler.rs index 4586d20f..f887e10e 100644 --- a/rustuna_sampler/src/tpe/sampler.rs +++ b/rustuna_sampler/src/tpe/sampler.rs @@ -760,7 +760,12 @@ impl TpeSampler { } impl Sampler for TpeSampler { - fn before_trial(&self, ctx: &Context, storage: Arc>) -> Result<()> { + fn before_trial( + &self, + ctx: &Context, + storage: Arc>, + _trial_queue: Arc, + ) -> Result<()> { let observations = self.snapshot_from_storage(ctx, &storage)?; let mut cache = self.observations_cache.write().map_err(|e| { Error::with_reason( @@ -795,6 +800,7 @@ impl Sampler for TpeSampler { &self, ctx: &Context, storage: Arc>, + trial_queue: Arc, name: &str, distribution: &Distribution, ) -> Result { @@ -804,9 +810,13 @@ impl Sampler for TpeSampler { let search_space = HashMap::from([(name.to_string(), distribution.clone())]); let Some(observations) = self.observations_for_trial(ctx, &storage)? else { - return self - .random_sampler - .sample_independent(ctx, storage, name, distribution); + return self.random_sampler.sample_independent( + ctx, + storage, + trial_queue, + name, + distribution, + ); }; let params = self.sample(ctx, &observations.view(&search_space))?; Ok(params[name]) @@ -824,6 +834,7 @@ impl Sampler for TpeSampler { &self, ctx: &Context, storage: Arc>, + _trial_queue: Arc, search_space: &HashMap, ) -> Result> { // Resolve the effective multivariate flag. Default (`None`) follows Optuna: multivariate @@ -850,6 +861,7 @@ impl Sampler for TpeSampler { &self, ctx: &Context, storage: Arc>, + _trial_queue: Arc, _state_values: &TrialStateValues, ) -> Result<()> { self.observations_cache @@ -877,6 +889,10 @@ mod tests { use rustuna_core::study::{create_study, Direction}; use rustuna_core::study::{get_best_trial, get_pareto_front}; + fn test_trial_queue() -> Arc { + Arc::new(rustuna_core::trial_queue::InMemoryTrialQueue::new()) + } + #[test] fn test_optimize() { let storage = InMemoryStorage::new(); @@ -1380,13 +1396,27 @@ mod tests { let distribution = Distribution::new_float(0.0, 10.0, None, false); let cached = TpeSampler::seed_from_u64(7); let direct = TpeSampler::seed_from_u64(7); - cached.before_trial(&ctx, study.storage.clone()).unwrap(); + cached + .before_trial(&ctx, study.storage.clone(), test_trial_queue()) + .unwrap(); for name in ["x", "y", "unobserved"] { let a = cached - .sample_independent(&ctx, study.storage.clone(), name, &distribution) + .sample_independent( + &ctx, + study.storage.clone(), + test_trial_queue(), + name, + &distribution, + ) .unwrap(); let b = direct - .sample_independent(&ctx, study.storage.clone(), name, &distribution) + .sample_independent( + &ctx, + study.storage.clone(), + test_trial_queue(), + name, + &distribution, + ) .unwrap(); assert_eq!(a, b); assert!((0.0..=10.0).contains(&a)); @@ -1397,10 +1427,20 @@ mod tests { ]); assert_eq!( cached - .sample_joint(&ctx, study.storage.clone(), &search_space) + .sample_joint( + &ctx, + study.storage.clone(), + test_trial_queue(), + &search_space, + ) .unwrap(), direct - .sample_joint(&ctx, study.storage.clone(), &search_space) + .sample_joint( + &ctx, + study.storage.clone(), + test_trial_queue(), + &search_space, + ) .unwrap() ); } @@ -1434,7 +1474,7 @@ mod tests { }; probe - .before_trial(&ctx(100), study.storage.clone()) + .before_trial(&ctx(100), study.storage.clone(), test_trial_queue()) .unwrap(); assert!(matches!( probe @@ -1450,7 +1490,7 @@ mod tests { .optimize(|mut t| Ok(vec![t.suggest_float("x", 0.0, 1.0)?]), 2) .unwrap(); probe - .before_trial(&ctx(101), study.storage.clone()) + .before_trial(&ctx(101), study.storage.clone(), test_trial_queue()) .unwrap(); assert!(matches!( probe @@ -1466,6 +1506,7 @@ mod tests { .after_trial( &ctx(101), study.storage.clone(), + test_trial_queue(), &TrialStateValues::Complete(vec![0.0]), ) .unwrap(); @@ -1478,7 +1519,7 @@ mod tests { for trial_id in 200..(200 + OBSERVATIONS_CACHE_CAP as u32 + 5) { probe - .before_trial(&ctx(trial_id), study.storage.clone()) + .before_trial(&ctx(trial_id), study.storage.clone(), test_trial_queue()) .unwrap(); } let cache = probe.observations_cache.read().unwrap(); @@ -1684,8 +1725,12 @@ mod tests { trial_number: 1, directions: vec![Direction::Minimize], }; - sampler.before_trial(&ctx, first.clone()).unwrap(); - sampler.before_trial(&ctx, second.clone()).unwrap(); + sampler + .before_trial(&ctx, first.clone(), test_trial_queue()) + .unwrap(); + sampler + .before_trial(&ctx, second.clone(), test_trial_queue()) + .unwrap(); let values = |storage: &Arc>| { sampler .observations_for_trial(&ctx, storage) @@ -1697,11 +1742,18 @@ mod tests { assert_eq!(values(&first), [1.0]); assert_eq!(values(&second), [9.0]); sampler - .after_trial(&ctx, first.clone(), &TrialStateValues::Fail) + .after_trial( + &ctx, + first.clone(), + test_trial_queue(), + &TrialStateValues::Fail, + ) .unwrap(); assert_eq!(values(&second), [9.0]); drop(first); - sampler.before_trial(&ctx, second).unwrap(); + sampler + .before_trial(&ctx, second, test_trial_queue()) + .unwrap(); assert_eq!(sampler.observations_cache.read().unwrap().studies.len(), 1); } @@ -1738,7 +1790,9 @@ mod tests { .create_new_trial_from_template(study_id, &trial) .unwrap(); for _ in 0..2 { - assert!(sampler.before_trial(&ctx, storage.clone()).is_err()); + assert!(sampler + .before_trial(&ctx, storage.clone(), test_trial_queue()) + .is_err()); let cache = sampler.observations_cache.read().unwrap(); assert!(cache.studies.is_empty()); assert!(cache.per_trial.is_empty()); @@ -1763,7 +1817,9 @@ mod tests { trial_number: 0, directions: vec![Direction::Minimize], }; - sampler.before_trial(&ctx, storage.clone()).unwrap(); + sampler + .before_trial(&ctx, storage.clone(), test_trial_queue()) + .unwrap(); } let cache = sampler.observations_cache.read().unwrap(); assert_eq!(cache.studies.len(), OBSERVATIONS_CACHE_CAP);