Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions rustuna_pyo3/rustuna/_rustuna.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -1183,6 +1183,7 @@ class SamplerContext:
trial_number: int,
trial_id: int,
directions: list[StudyDirection],
trial_queue: TrialQueueProtocol,
) -> None: ...

class RandomSampler:
Expand Down
42 changes: 18 additions & 24 deletions rustuna_pyo3/rustuna/converter/_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,7 @@ def sample_relative(
if search_space == {}:
return {}

ctx = rustuna.samplers.SamplerContext(
study_id=study._study_id,
trial_number=trial.number,
trial_id=trial._trial_id,
directions=to_rustuna_directions(study._directions),
)
ctx = _create_rustuna_sampler_context(study, trial)
storage = self._get_storage(study._storage)
# 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
Expand All @@ -96,12 +91,7 @@ def sample_relative(

def before_trial(self, study: Study, trial: FrozenTrial) -> None:
"""Run pre-processing in the Rustuna sampler before search-space inference."""
ctx = rustuna.samplers.SamplerContext(
study_id=study._study_id,
trial_number=trial.number,
trial_id=trial._trial_id,
directions=to_rustuna_directions(study._directions),
)
ctx = _create_rustuna_sampler_context(study, trial)
storage = self._get_storage(study._storage)
self._sampler.before_trial(ctx, storage)

Expand All @@ -113,12 +103,7 @@ def sample_independent(
param_distribution: BaseDistribution,
) -> Any:
"""Sample one parameter using the Rustuna sampler."""
ctx = rustuna.samplers.SamplerContext(
study_id=study._study_id,
trial_number=trial.number,
trial_id=trial._trial_id,
directions=to_rustuna_directions(study._directions),
)
ctx = _create_rustuna_sampler_context(study, trial)
storage = self._get_storage(study._storage)
distribution = to_rustuna_distribution(param_distribution)
internal_param = self._sampler.sample_independent(
Expand Down Expand Up @@ -155,16 +140,25 @@ def after_trial(
values: Sequence[float] | None,
) -> None:
"""Notify the Rustuna sampler that a trial has finished."""
ctx = rustuna.samplers.SamplerContext(
study_id=study._study_id,
trial_number=trial.number,
trial_id=trial._trial_id,
directions=to_rustuna_directions(study._directions),
)
ctx = _create_rustuna_sampler_context(study, trial)
storage = self._get_storage(study._storage)
self._sampler.after_trial(
ctx,
storage,
to_rustuna_state(state),
list(values) if values is not None else None,
)


def _create_rustuna_sampler_context(
study: Study, trial: FrozenTrial
) -> rustuna.samplers.SamplerContext:
# Optuna studies have no trial queue, so trials enqueued by the Rustuna sampler
# are never asked for. A new queue per context keeps them from piling up.
return rustuna.samplers.SamplerContext(
study_id=study._study_id,
trial_number=trial.number,
trial_id=trial._trial_id,
directions=to_rustuna_directions(study._directions),
trial_queue=rustuna.trial_queue.InMemoryTrialQueue(),
)
9 changes: 6 additions & 3 deletions rustuna_pyo3/src/sampler/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ use std::sync::Arc;
use pyo3::prelude::*;

use rustuna_core::sampler::Context as SamplerContext;
use rustuna_core::trial_queue::InMemoryTrialQueue;

use crate::study::PyDirection;
use crate::trial_queue::into_trial_queue_pyobj;
use crate::trial_queue::to_python::ToPythonTrialQueue;

#[derive(Clone)]
Expand All @@ -23,20 +23,23 @@ impl From<SamplerContext> for PySamplerContext {
#[pymethods]
impl PySamplerContext {
#[new]
#[pyo3(signature = (*, study_id, trial_number, trial_id, directions))]
#[pyo3(signature = (*, study_id, trial_number, trial_id, directions, trial_queue))]
pub fn py_new(
py: Python<'_>,
study_id: u32,
trial_number: u32,
trial_id: u32,
directions: Vec<PyDirection>,
trial_queue: Py<PyAny>,
) -> PyResult<Self> {
let (trial_queue, _) = into_trial_queue_pyobj(py, Some(trial_queue))?;
Ok(PySamplerContext {
context: SamplerContext {
study_id,
trial_number,
trial_id,
directions: directions.into_iter().map(|d| d.into()).collect(),
trial_queue: Arc::new(InMemoryTrialQueue::new()),
trial_queue,
},
})
}
Expand Down
46 changes: 1 addition & 45 deletions rustuna_pyo3/src/study.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,11 @@ use crate::storage::sqlite3::PySQLite3Storage;
use crate::storage::to_python::ToPythonStorage;
use crate::storage::to_rust::ToRustStorage;
use crate::trial::{PyPersistedTrial, PyTrial, PyTrialState};
use crate::trial_queue::directory::PyDirectoryTrialQueue;
use crate::trial_queue::inmemory::PyInMemoryTrialQueue;
use crate::trial_queue::sqlite3::PySQLite3TrialQueue;
use crate::trial_queue::to_rust::ToRustTrialQueue;
use crate::trial_queue::into_trial_queue_pyobj;

type SharedStorage = Arc<RwLock<dyn Storage>>;
type SharedSampler = Arc<dyn Sampler>;
type SharedTrialQueue = Arc<dyn rustuna_core::trial_queue::TrialQueue>;

mod py_exceptions {
pyo3::import_exception!(rustuna.exceptions, TrialPruned);
Expand Down Expand Up @@ -146,47 +143,6 @@ fn matches_any_exception(py: Python<'_>, err: &PyErr, catch: &[Py<PyAny>]) -> Py
Ok(false)
}

fn into_trial_queue_pyobj(
py: Python<'_>,
trial_queue: Option<Py<PyAny>>,
) -> PyResult<(SharedTrialQueue, Py<PyAny>)> {
match trial_queue {
Some(trial_queue) => {
let trial_queue_ref = trial_queue.bind(py);
if let Ok(py_inmemory_trial_queue) = trial_queue_ref.extract::<PyInMemoryTrialQueue>() {
Ok((
py_inmemory_trial_queue.queue.clone() as SharedTrialQueue,
trial_queue.clone_ref(py),
))
} else if let Ok(py_sqlite3_trial_queue) =
trial_queue_ref.extract::<PySQLite3TrialQueue>()
{
Ok((
py_sqlite3_trial_queue.queue.clone() as SharedTrialQueue,
trial_queue.clone_ref(py),
))
} else if let Ok(py_directory_trial_queue) =
trial_queue_ref.extract::<PyDirectoryTrialQueue>()
{
Ok((
py_directory_trial_queue.queue.clone() as SharedTrialQueue,
trial_queue.clone_ref(py),
))
} else {
let queue: SharedTrialQueue =
Arc::new(ToRustTrialQueue::new(trial_queue.clone_ref(py)));
Ok((queue, trial_queue.clone_ref(py)))
}
}
None => {
let trial_queue = PyInMemoryTrialQueue::new();
let queue = trial_queue.queue.clone();
let py_trial_queue = Py::new(py, trial_queue)?.into_any();
Ok((queue, py_trial_queue))
}
}
}

fn resolve_storage_pyobj(
py: Python<'_>,
storage: Py<PyAny>,
Expand Down
56 changes: 56 additions & 0 deletions rustuna_pyo3/src/trial_queue/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,61 @@
use std::sync::Arc;

use pyo3::prelude::*;

use crate::trial_queue::directory::PyDirectoryTrialQueue;
use crate::trial_queue::inmemory::PyInMemoryTrialQueue;
use crate::trial_queue::sqlite3::PySQLite3TrialQueue;
use crate::trial_queue::to_rust::ToRustTrialQueue;

pub mod directory;
pub mod inmemory;
pub mod sqlite3;
pub(crate) mod to_python;
pub mod to_rust;

pub(crate) type SharedTrialQueue = Arc<dyn rustuna_core::trial_queue::TrialQueue>;

/// Resolves a Python trial queue into a Rust trial queue and the Python object that owns it.
///
/// Built-in queues share their Rust queue directly, other objects are wrapped in
/// `ToRustTrialQueue`, and `None` creates a new in-memory queue.
pub(crate) fn into_trial_queue_pyobj(
py: Python<'_>,
trial_queue: Option<Py<PyAny>>,
) -> PyResult<(SharedTrialQueue, Py<PyAny>)> {
match trial_queue {
Some(trial_queue) => {
let trial_queue_ref = trial_queue.bind(py);
if let Ok(py_inmemory_trial_queue) = trial_queue_ref.extract::<PyInMemoryTrialQueue>() {
Ok((
py_inmemory_trial_queue.queue.clone() as SharedTrialQueue,
trial_queue.clone_ref(py),
))
} else if let Ok(py_sqlite3_trial_queue) =
trial_queue_ref.extract::<PySQLite3TrialQueue>()
{
Ok((
py_sqlite3_trial_queue.queue.clone() as SharedTrialQueue,
trial_queue.clone_ref(py),
))
} else if let Ok(py_directory_trial_queue) =
trial_queue_ref.extract::<PyDirectoryTrialQueue>()
{
Ok((
py_directory_trial_queue.queue.clone() as SharedTrialQueue,
trial_queue.clone_ref(py),
))
} else {
let queue: SharedTrialQueue =
Arc::new(ToRustTrialQueue::new(trial_queue.clone_ref(py)));
Ok((queue, trial_queue.clone_ref(py)))
}
}
None => {
let trial_queue = PyInMemoryTrialQueue::new();
let queue = trial_queue.queue.clone();
let py_trial_queue = Py::new(py, trial_queue)?.into_any();
Ok((queue, py_trial_queue))
}
}
}
1 change: 1 addition & 0 deletions rustuna_pyo3/tests/sampler_tests/test_cmaes.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ def test_cmaes_sampler_samples_independently_from_multiple_threads() -> None:
trial_number=0,
trial_id=0,
directions=study.directions,
trial_queue=study.trial_queue,
)
distribution = rustuna.distributions.FloatDistribution(-1, 1)

Expand Down
1 change: 1 addition & 0 deletions rustuna_pyo3/tests/storage_tests/test_journal_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ def test_journal_file_storage_can_be_used_by_native_sampler() -> None:
trial_number=trial.number,
trial_id=trial._trial_id,
directions=study.directions,
trial_queue=study.trial_queue,
)

value = rustuna.samplers.RandomSampler(seed=1).sample_independent(
Expand Down
1 change: 1 addition & 0 deletions rustuna_pyo3/tests/test_rustuna.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,7 @@ def test_sample():
trial_number=trial.number,
trial_id=trial._trial_id,
directions=study.directions,
trial_queue=study.trial_queue,
)
value = sampler.sample_independent(
ctx, storage, "x", rustuna.distributions.FloatDistribution(0, 1)
Expand Down
Loading