Skip to content
Closed
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
20 changes: 19 additions & 1 deletion rustuna_core/src/sampler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,12 @@
///
/// 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<RwLock<dyn Storage>>) -> Result<()> {
fn before_trial(
&self,
_ctx: &Context,
_storage: Arc<RwLock<dyn Storage>>,
_trial_queue: Arc<dyn crate::trial_queue::TrialQueue>,
) -> Result<()> {
Ok(())
}

Expand All @@ -55,6 +60,7 @@
&self,
ctx: &Context,
storage: Arc<RwLock<dyn Storage>>,
trial_queue: Arc<dyn crate::trial_queue::TrialQueue>,
name: &str,
distribution: &Distribution,
) -> Result<f64>;
Expand All @@ -71,6 +77,7 @@
&self,
ctx: &Context,
storage: Arc<RwLock<dyn Storage>>,
trial_queue: Arc<dyn crate::trial_queue::TrialQueue>,
search_space: &HashMap<String, Distribution>,
) -> Result<HashMap<String, f64>>;
/// Hook called when a trial is about to be finalized with the given state.
Expand All @@ -81,6 +88,7 @@
&self,
_ctx: &Context,
_storage: Arc<RwLock<dyn Storage>>,
_trial_queue: Arc<dyn crate::trial_queue::TrialQueue>,
_state_values: &TrialStateValues,
) -> Result<()> {
Ok(())
Expand Down Expand Up @@ -175,6 +183,7 @@
&self,
_ctx: &Context,
_storage: Arc<RwLock<dyn Storage>>,
_trial_queue: Arc<dyn crate::trial_queue::TrialQueue>,
_name: &str,
distribution: &Distribution,
) -> Result<f64> {
Expand Down Expand Up @@ -223,6 +232,7 @@
&self,
_ctx: &Context,
_storage: Arc<RwLock<dyn Storage>>,
_trial_queue: Arc<dyn crate::trial_queue::TrialQueue>,
_search_space: &HashMap<String, Distribution>,
) -> Result<HashMap<String, f64>> {
unreachable!()
Expand All @@ -232,6 +242,7 @@
&self,
_ctx: &Context,
_storage: Arc<RwLock<dyn Storage>>,
_trial_queue: Arc<dyn crate::trial_queue::TrialQueue>,
_state_values: &TrialStateValues,
) -> Result<()> {
Ok(())
Expand All @@ -246,6 +257,7 @@
use crate::storage::InMemoryStorage;
use crate::study::create_study;
use crate::trial::Trial;
use crate::trial_queue::InMemoryTrialQueue;

pub struct DummyJointSampler {
joint_params: HashMap<String, f64>,
Expand All @@ -255,6 +267,7 @@
&self,
_ctx: &Context,
_storage: Arc<RwLock<dyn Storage>>,
_trial_queue: Arc<dyn crate::trial_queue::TrialQueue>,
_name: &str,
_distribution: &Distribution,
) -> Result<f64> {
Expand All @@ -269,6 +282,7 @@
&self,
_ctx: &Context,
_storage: Arc<RwLock<dyn Storage>>,
_trial_queue: Arc<dyn crate::trial_queue::TrialQueue>,
_search_space: &HashMap<String, Distribution>,
) -> Result<HashMap<String, f64>> {
Ok(self.joint_params.clone())
Expand All @@ -278,6 +292,7 @@
&self,
_ctx: &Context,
_storage: Arc<RwLock<dyn Storage>>,
_trial_queue: Arc<dyn crate::trial_queue::TrialQueue>,
_state_values: &TrialStateValues,
) -> Result<()> {
Ok(())
Expand All @@ -294,12 +309,14 @@
fn random_sampler_can_be_shared_between_threads() -> Result<()> {
let sampler: Arc<dyn Sampler> = Arc::new(RandomSampler::seed_from_u64(0));
let storage: Arc<RwLock<dyn Storage>> = Arc::new(RwLock::new(InMemoryStorage::new()));
let trial_queue: Arc<dyn TrialQueue> = Arc::new(InMemoryTrialQueue::new());

Check failure on line 312 in rustuna_core/src/sampler.rs

View workflow job for this annotation

GitHub Actions / rust_test

cannot find trait `TrialQueue` in this scope

Check failure on line 312 in rustuna_core/src/sampler.rs

View workflow job for this annotation

GitHub Actions / rust_lint

cannot find trait `TrialQueue` in this scope
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 {
Expand All @@ -312,6 +329,7 @@
let value = sampler.sample_independent(
&ctx,
Arc::clone(&storage),
Arc::clone(&trial_queue),
"x",
&distribution,
)?;
Expand Down
25 changes: 18 additions & 7 deletions rustuna_core/src/study.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, (Distribution, f64)> =
if self.sampler.support_joint_sampling() {
Expand All @@ -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) {
Expand All @@ -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)
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -579,6 +587,7 @@ mod tests {
&self,
_ctx: &SamplerContext,
_storage: Arc<RwLock<dyn Storage>>,
_trial_queue: Arc<dyn TrialQueue>,
_name: &str,
_distribution: &Distribution,
) -> Result<f64> {
Expand All @@ -593,6 +602,7 @@ mod tests {
&self,
_ctx: &SamplerContext,
_storage: Arc<RwLock<dyn Storage>>,
_trial_queue: Arc<dyn TrialQueue>,
_search_space: &HashMap<String, Distribution>,
) -> Result<HashMap<String, f64>> {
unreachable!()
Expand All @@ -602,6 +612,7 @@ mod tests {
&self,
ctx: &SamplerContext,
storage: Arc<RwLock<dyn Storage>>,
_trial_queue: Arc<dyn TrialQueue>,
state_values: &TrialStateValues,
) -> Result<()> {
let mut storage_guard = storage.write().map_err(|e| {
Expand Down
14 changes: 11 additions & 3 deletions rustuna_core/src/trial.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -27,6 +28,7 @@ pub struct Trial {
directions: Vec<Direction>,
storage: Arc<RwLock<dyn Storage>>,
sampler: Arc<dyn Sampler>,
trial_queue: Arc<dyn TrialQueue>,
joint_params: HashMap<String, (Distribution, f64)>,
fixed_params: HashMap<String, CategoryLabel>,
cached_user_attrs: HashMap<String, String>,
Expand All @@ -38,6 +40,7 @@ impl Trial {
directions: Vec<Direction>,
storage: Arc<RwLock<dyn Storage>>,
sampler: Arc<dyn Sampler>,
trial_queue: Arc<dyn TrialQueue>,
joint_params: HashMap<String, (Distribution, f64)>,
) -> Self {
let fixed_params = extract_fixed_params(&trial.attrs);
Expand All @@ -58,6 +61,7 @@ impl Trial {
directions,
storage,
sampler,
trial_queue,
joint_params,
fixed_params,
cached_user_attrs,
Expand Down Expand Up @@ -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(
Expand Down
9 changes: 9 additions & 0 deletions rustuna_pyo3/rustuna/_protocols.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -26,13 +27,15 @@ def sample_joint(
self,
ctx: SamplerContext,
storage: StorageProtocol,
trial_queue: TrialQueueProtocol,
search_space: dict[str, Distribution],
) -> dict[str, float]:
"""Sample multiple parameters simultaneously.

Args:
ctx: Sampler context.
storage: Storage object.
trial_queue: Trial queue shared by this study.
search_space: Parameter distributions.

Returns:
Expand All @@ -43,6 +46,7 @@ def before_trial(
self,
ctx: SamplerContext,
storage: StorageProtocol,
trial_queue: TrialQueueProtocol,
) -> None:
"""Run sampler pre-processing before search-space inference.

Expand All @@ -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:
Expand All @@ -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.

Expand All @@ -77,6 +84,7 @@ def after_trial(
self,
ctx: SamplerContext,
storage: StorageProtocol,
trial_queue: TrialQueueProtocol,
state: TrialState,
values: list[float] | None = None,
) -> None:
Expand All @@ -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.
"""
Expand Down
Loading
Loading