A programming framework for agentic AI
fix onlineaml docstr
Qingyun Wu09e75c9b9c1f
diff --git a/flaml/onlineml/autovw.py b/flaml/onlineml/autovw.pyindex d82ba555a..dbb611b13 100644--- a/flaml/onlineml/autovw.py+++ b/flaml/onlineml/autovw.py@@ -16,7 +16,7 @@ logger = logging.getLogger(__name__)class AutoVW:- """The AutoML class."""+ """class for the AutoVW algorithm."""WARMSTART_NUM = 100AUTOMATIC = "_auto"@@ -39,42 +39,50 @@ class AutoVW:"""Constructor.Args:- max_live_model_num: The maximum number of 'live' models, which, in other words,- is the maximum number of models allowed to update in each learning iteraction.- search_space: A dictionary of the search space. This search space includes both- hyperparameters we want to tune and fixed hyperparameters. In the latter case,- the value is a fixed value.+ max_live_model_num: An int to specify the maximum number of+ 'live' models, which, in other words, is the maximum number+ of models allowed to update in each learning iteraction.+ search_space: A dictionary of the search space. This search space+ includes both hyperparameters we want to tune and fixed+ hyperparameters. In the latter case, the value is a fixed value.init_config: A dictionary of a partial or full initial config,e.g. {'interactions': set(), 'learning_rate': 0.5}- min_resource_lease: The minimum resource lease assigned to a particular model/trial.- If set as 'auto', it will be calculated automatically.+ min_resource_lease: string or float | The minimum resource lease+ assigned to a particular model/trial. If set as 'auto', it will+ be calculated automatically.automl_runner_args: A dictionary of configuration for the OnlineTrialRunner.- If set {}, default values will be used, which is equivalent to using the following configs.- ```python- automl_runner_args =- {"champion_test_policy": 'loss_ucb' # specifcies how to do the statistic test for a better champion- "remove_worse": False # specifcies whether to do worse than test+ If set {}, default values will be used, which is equivalent to using+ the following configs.+ .. code-block:: python++ automl_runner_args =+ {"champion_test_policy": 'loss_ucb',# the statistic test for a better champion+ "remove_worse": False, # whether to do worse than test}- ```+scheduler_args: A dictionary of configuration for the scheduler.- If set {}, default values will be used, which is equivalent to using the following configs.- ```python- scheduler_args =- {"keep_challenger_metric": 'ucb' # what metric to use when deciding the top performing challengers- "keep_challenger_ratio": 0.5 # denotes the ratio of top performing challengers to keep live- "keep_champion": True # specifcies whether to keep the champion always running+ If set {}, default values will be used, which is equivalent to using the+ following config.+ .. code-block:: python++ scheduler_args =+ {"keep_challenger_metric": 'ucb', # what metric to use when deciding the top performing challengers+ "keep_challenger_ratio": 0.5, # denotes the ratio of top performing challengers to keep live+ "keep_champion": True, # specifcies whether to keep the champion always running}- ```- model_select_policy: A string in ['threshold_loss_ucb', 'threshold_loss_lcb', 'threshold_loss_avg',- 'loss_ucb', 'loss_lcb', 'loss_avg'] to specify how to select one model to do prediction- from the live model pool. Default value is 'threshold_loss_ucb'.- metric: A string in ['mae_clipped', 'mae', 'mse', 'absolute_clipped', 'absolute', 'squared']- to specify the name of the loss function used for calculating the progressive validation loss in ChaCha.- random_seed (int): An integer of the random seed used in the searcher++ model_select_policy: A string in ['threshold_loss_ucb',+ 'threshold_loss_lcb', 'threshold_loss_avg', 'loss_ucb', 'loss_lcb',+ 'loss_avg'] to specify how to select one model to do prediction from+ the live model pool. Default value is 'threshold_loss_ucb'.+ metric: A string in ['mae_clipped', 'mae', 'mse', 'absolute_clipped',+ 'absolute', 'squared'] to specify the name of the loss function used+ for calculating the progressive validation loss in ChaCha.+ random_seed: An integer of the random seed used in the searcher(more specifically this the random seed for ConfigOracle).model_selection_mode: A string in ['min', 'max'] to specify the objective asminimization or maximization.- cb_coef (float): A float coefficient (optional) used in the sample complexity bound.+ cb_coef: A float coefficient (optional) used in the sample complexity bound."""self._max_live_model_num = max_live_model_numself._search_space = search_space@@ -96,7 +104,7 @@ class AutoVW:self._iter = 0def _setup_trial_runner(self, vw_example):- """Set up the _trial_runner based on one vw_example"""+ """Set up the _trial_runner based on one vw_example."""# setup the default search space for the namespace interaction hyperparametersearch_space = self._search_space.copy()for k, v in self._search_space.items():@@ -136,10 +144,10 @@ class AutoVW:)def predict(self, data_sample):- """Predict on the input example (e.g., vw example).+ """Predict on the input data sample.Args:- data_sample: vw_example.+ data_sample: one data example in vw format."""if self._trial_runner is None:self._setup_trial_runner(data_sample)@@ -163,13 +171,14 @@ class AutoVW:"""Perform one online learning step with the given data sample.Args:- data_sample (vw_example): one data sample on which the model gets updated.+ data_sample: one data example in vw format. It will be used to+ update the vw model."""self._iter += 1self._trial_runner.step(data_sample, (self._y_predict, self._best_trial))def _select_best_trial(self):- """Select a best trial from the running trials accoring to the _model_select_policy."""+ """Select a best trial from the running trials according to the _model_select_policy."""best_score = (float("+inf") if self._model_selection_mode == "min" else float("-inf"))diff --git a/flaml/onlineml/trial.py b/flaml/onlineml/trial.pyindex f61c0286d..5d4feafb3 100644--- a/flaml/onlineml/trial.py+++ b/flaml/onlineml/trial.py@@ -12,22 +12,21 @@ logger = logging.getLogger(__name__)def get_ns_feature_dim_from_vw_example(vw_example) -> dict:- """Get a dictionary of feature dimensionality for each namespace singleton.+ """Get a dictionary of feature dimensionality for each namespace singleton."""+ # *************************A NOTE about the input vwexample***********+ # Assumption: assume the vw_example takes one of the following format+ # depending on whether the example includes the feature names.- NOTE:- Assumption: assume the vw_example takes one of the following format- depending on whether the example includes the feature names.+ # format 1: `y |ns1 feature1:feature_value1 feature2:feature_value2 |ns2+ # ns2 feature3:feature_value3 feature4:feature_value4`+ # format 2: `y | ns1 feature_value1 feature_value2 |+ # ns2 feature_value3 feature_value4`- format 1: `y |ns1 feature1:feature_value1 feature2:feature_value2 |ns2- ns2 feature3:feature_value3 feature4:feature_value4`- format 2: `y | ns1 feature_value1 feature_value2 |- ns2 feature_value3 feature_value4`+ # The output of both cases are `{'ns1': 2, 'ns2': 2}`.- The output of both cases are `{'ns1': 2, 'ns2': 2}`.+ # For more information about the input formate of vw example, please refer to+ # https://github.com/VowpalWabbit/vowpal_wabbit/wiki/Input-format.- For more information about the input formate of vw example, please refer to- https://github.com/VowpalWabbit/vowpal_wabbit/wiki/Input-format.- """ns_feature_dim = {}data = vw_example.split("|")for i in range(1, len(data)):@@ -48,18 +47,7 @@ def get_ns_feature_dim_from_vw_example(vw_example) -> dict:class OnlineResult:- """Class for managing the result statistics of a trial.-- Attributes:- observation_count: the total number of observations- resource_used: the sum of loss.-- Methods:- * update_result(new_loss, new_resource_used, data_dimension):- Update result.- * get_score(score_name):- Get the score according to the input score_name.- """+ """class for managing the result statistics of a trial."""prob_delta = 0.1LOSS_MIN = 0.0@@ -75,9 +63,17 @@ class OnlineResult:mode: Optional[str] = "min",sliding_window_size: Optional[int] = 100,):- """+ """Constructor.+Args:- result_type_name (str): The name of the result type.+ result_type_name: A String to specify the name of the result type.+ cb_coef: a string to specify the coefficient on the confidence bound.+ init_loss: a float to specify the inital loss.+ init_cb: a float to specify the intial confidence bound.+ mode: A string in ['min', 'max'] to specify the objective as+ minimization or maximization.+ sliding_window_size: An int to specify the size of the sliding windown+ (for experimental purpose)."""self._result_type_name = result_type_name # for example 'mse' or 'mae'self._mode = mode@@ -113,7 +109,7 @@ class OnlineResult:def _update_loss_cb(self, bound_of_range, data_dim, bound_name="sample_complexity_bound"):- """Calculate bound coef."""+ """Calculate the coefficient of the confidence bound."""if bound_name == "sample_complexity_bound":# set the coefficient in the loss boundif "mae" in self.result_type_name:@@ -169,21 +165,7 @@ class OnlineResult:class BaseOnlineTrial(Trial):- """Class for online trial.-- Attributes:- * config: the config for this trial.- * trial_id: the trial_id of this trial.- * min_resource_lease (float): the minimum resource realse.- * status: the status of this trial.- * start_time: the start time of this trial.- * custom_trial_name: a custom name for this trial.-- Methods:- * set_resource_lease(resource)- * set_status(status)- * set_checked_under_current_champion(checked_under_current_champion)- """+ """Class for the online trial."""def __init__(self,@@ -194,14 +176,16 @@ class BaseOnlineTrial(Trial):custom_trial_name: Optional[str] = "mae",trial_id: Optional[str] = None,):- """+ """Constructor.+Args:- config: the config dict.- min_resource_lease: the minimum resource realse.- is_champion: a bool variable.- is_checked_under_current_champion: a bool variable.- custom_trial_name: custom trial name.- trial_id: the trial id.+ config: The configuration dictionary.+ min_resource_lease: A float specifying the minimum resource lease.+ is_champion: A bool variable indicating whether the trial is champion.+ is_checked_under_current_champion: A bool indicating whether the trial+ has been used under the current champion.+ custom_trial_name: A string of a custom trial name.+ trial_id: A string for the trial id."""# ****basic variablesself.config = config@@ -231,21 +215,21 @@ class BaseOnlineTrial(Trial):return self._resource_leasedef set_checked_under_current_champion(self, checked_under_current_champion: bool):- """This is needed because sometimes- we want to know whether a trial has been paused since a new champion is promoted.- We want to try to pause those running trials (even though they are not yet achieve- the next scheduling check point according to resource used and resource lease),- because a better trial is likely to be in the new challengers generated by the new- champion, so we want to try them as soon as possible.- If we wait until we reach the next scheduling point, we may waste a lot of resource- (depending on what is the current resource lease) on the old trials (note that new- trials is not possible to be scheduled to run until there is a slot openning).- Intuitively speaking, we want to squize an opening slot as soon as possible once- a new champion is promoted, such that we are able to try newly generated challengers.- """+ # This is needed because sometimes+ # we want to know whether a trial has been paused since a new champion is promoted.+ # We want to try to pause those running trials (even though they are not yet achieve+ # the next scheduling check point according to resource used and resource lease),+ # because a better trial is likely to be in the new challengers generated by the new+ # champion, so we want to try them as soon as possible.+ # If we wait until we reach the next scheduling point, we may waste a lot of resource+ # (depending on what is the current resource lease) on the old trials (note that new+ # trials is not possible to be scheduled to run until there is a slot openning).+ # Intuitively speaking, we want to squize an opening slot as soon as possible once+ # a new champion is promoted, such that we are able to try newly generated challengers.self._is_checked_under_current_champion = checked_under_current_championdef set_resource_lease(self, resource: float):+ """Sets the resource lease accordingly."""self._resource_lease = resourcedef set_status(self, status):@@ -257,36 +241,17 @@ class BaseOnlineTrial(Trial):class VowpalWabbitTrial(BaseOnlineTrial):- """Implement BaseOnlineTrial for Vowpal Wabbit.-- Attributes:- * model: the online model.- * result: the anytime result for the online model.- * trainable_class: the model class (set as pyvw.vw for VowpalWabbitTrial).- * config: the config for this trial.- * trial_id: the trial_id of this trial.- * min_resource_lease (float): the minimum resource realse.- * status: the status of this trial.- * start_time: the start time of this trial.- * custom_trial_name: a custom name for this trial.-- Methods:- * set_resource_lease(resource)- * set_status(status)- * set_checked_under_current_champion(checked_under_current_champion)-- NOTE:- About result:- 1. training related results (need to be updated in the trainable class)- 2. result about resources lease (need to be updated externally)-- About namespaces in vw:- - Wiki in vw:- https://github.com/VowpalWabbit/vowpal_wabbit/wiki/Namespaces- - Namespace vs features:- https://stackoverflow.com/questions/28586225/in-vowpal-wabbit-what-is-the-difference-between-a-namespace-and-feature- """+ """The class for Vowpal Wabbit online trials."""++ # NOTE: 1. About namespaces in vw:+ # - Wiki in vw:+ # https://github.com/VowpalWabbit/vowpal_wabbit/wiki/Namespaces+ # - Namespace vs features:+ # https://stackoverflow.com/questions/28586225/in-vowpal-wabbit-what-is-the-difference-between-a-namespace-and-feature+ # About result:+ # 1. training related results (need to be updated in the trainable class)+ # 2. result about resources lease (need to be updated externally)cost_unit = 1.0interactions_config_key = "interactions"MIN_RES_CONST = 5@@ -383,7 +348,7 @@ class VowpalWabbitTrial(BaseOnlineTrial):)def train_eval_model_online(self, data_sample, y_pred):- """Train and eval model online."""+ """Train and evaluate model online."""# extract info needed the first time we see the dataif self._resource_lease == "auto" or self._resource_lease is None:assert self._dim is not Nonediff --git a/flaml/onlineml/trial_runner.py b/flaml/onlineml/trial_runner.pyindex bb07fad08..5510ac977 100644--- a/flaml/onlineml/trial_runner.py+++ b/flaml/onlineml/trial_runner.py@@ -9,42 +9,25 @@ logger = logging.getLogger(__name__)class OnlineTrialRunner:- """The OnlineTrialRunner class.-- Methods:- * step(max_live_model_num, data_sample, prediction_trial_tuple):- Outputs a _max_live_model_num number of trials to run each time it is called.- * get_top_running_trials():- Get a list of trial ids, whose performance is among the top running trials.- * add_trial(trial):- Add trial to this TrialRunner.- * stop_trial(trial):- Set the status of a trial to be Trial.TERMINATED and perform other subsequent operations.- * pause_trial(trial):- Set the status of a trial to be Trial.PAUSED and perform other subsequent operations.- * run_trial(trial):- Set the status of a trial to be Trial.RUNNING and perform other subsequent operations.- * get_trials()- Get all the trials added (whatever that status) in the the OnlineTrialRunner.-- NOTE about the status of a trial:- Trial.PENDING: All trials are set to be pending when frist added into the OnlineTrialRunner until- it is selected to run. By this definition, a trial with status Trial.PENDING is a challenger- trial added to the OnlineTrialRunner but never been selected to run.- It denotes the starting of trial's lifespan in the OnlineTrialRunner.- Trial.RUNNING: It indicates that this trial is one of the concurrently running trials.- The max number of Trial.RUNNING trials is running_budget.- The status of a trial will be set to Trial.RUNNING the next time it selected to run.- A trial's status may have the following change:- Trial.PENDING -> Trial.RUNNING- Trial.PAUSED - > Trial.RUNNING- Trial.PAUSED: The status of a trial is set to Trial.PAUSED once it is removed from the running trials.- Trial.RUNNING - > Trial.PAUSED- Trial.TERMINATED: set the status of a trial to Trial.TERMINATED when you never want to select it.- It denotes the real end of a trial's lifespan.- Status change routine of a trial:- Trial.PENDING -> (Trial.RUNNING -> Trial.PAUSED -> Trial.RUNNING -> ...) -> Trial.TERMINATED(optional)- """+ """class for the OnlineTrialRunner."""++ # ************NOTE about the status of a trial***************+ # Trial.PENDING: All trials are set to be pending when frist added into the OnlineTrialRunner until+ # it is selected to run. By this definition, a trial with status Trial.PENDING is a challenger+ # trial added to the OnlineTrialRunner but never been selected to run.+ # It denotes the starting of trial's lifespan in the OnlineTrialRunner.+ # Trial.RUNNING: It indicates that this trial is one of the concurrently running trials.+ # The max number of Trial.RUNNING trials is running_budget.+ # The status of a trial will be set to Trial.RUNNING the next time it selected to run.+ # A trial's status may have the following change:+ # Trial.PENDING -> Trial.RUNNING+ # Trial.PAUSED - > Trial.RUNNING+ # Trial.PAUSED: The status of a trial is set to Trial.PAUSED once it is removed from the running trials.+ # Trial.RUNNING - > Trial.PAUSED+ # Trial.TERMINATED: set the status of a trial to Trial.TERMINATED when you never want to select it.+ # It denotes the real end of a trial's lifespan.+ # Status change routine of a trial:+ # Trial.PENDING -> (Trial.RUNNING -> Trial.PAUSED -> Trial.RUNNING -> ...) -> Trial.TERMINATED(optional)RANDOM_SEED = 123456WARMSTART_NUM = 100@@ -61,29 +44,33 @@ class OnlineTrialRunner:Args:max_live_model_num: The maximum number of 'live'/running models allowed.- searcher: A class for generating Trial objects progressively. The ConfigOracle- is implemented in the searcher.- Required methods of the searcher:- - next_trial()- Generate the next trial to add.- - set_search_properties(metric: Optional[str], mode: Optional[str], config: Optional[dict], setting: Optional[dict])- Generate new challengers based on the current champion and update the challenger list- - on_trial_result(trial_id: str, result: Dict)- Reprot results to the scheduler.- scheduler: A class for managing the 'live' trials and allocating the resources for the trials.- Required methods of the scheduler:- - on_trial_add(trial_runner, trial: Trial)- It adds candidate trials to the scheduler. It is called inside of the add_trial- function in the TrialRunner.- - on_trial_remove(trial_runner, trial: Trial)- Remove terminated trials from the scheduler.- - on_trial_result(trial_runner, trial: Trial, result: Dict)- Reprot results to the scheduler.- - choose_trial_to_run(trial_runner) -> Optional[Trial]- Among them, on_trial_result and choose_trial_to_run are the most important methods- champion_test_policy: A string to specify what test policy to test for champion.- Currently can choose from ['loss_ucb', 'loss_avg', 'loss_lcb', None].+ searcher: A class for generating Trial objects progressively.+ The ConfigOracle is implemented in the searcher.+ scheduler: A class for managing the 'live' trials and allocating the+ resources for the trials.+ champion_test_policy: A string to specify what test policy to test for+ champion. Currently can choose from ['loss_ucb', 'loss_avg', 'loss_lcb', None]."""+ # ************A NOTE about the input searcher and scheduler******+ # Required methods of the searcher:+ # - next_trial()+ # Generate the next trial to add.+ # - set_search_properties(metric: Optional[str], mode: Optional[str],+ # config: Optional[dict], setting: Optional[dict])+ # Generate new challengers based on the current champion and update the challenger list+ # - on_trial_result(trial_id: str, result: Dict)+ # Reprot results to the scheduler.+ # Required methods of the scheduler:+ # - on_trial_add(trial_runner, trial: Trial)+ # It adds candidate trials to the scheduler. It is called inside of the add_trial+ # function in the TrialRunner.+ # - on_trial_remove(trial_runner, trial: Trial)+ # Remove terminated trials from the scheduler.+ # - on_trial_result(trial_runner, trial: Trial, result: Dict)+ # Reprot results to the scheduler.+ # - choose_trial_to_run(trial_runner) -> Optional[Trial]+ # Among them, on_trial_result and choose_trial_to_run are the most important methods+ # *****************************************************************# OnlineTrialRunner settingself._searcher = searcherself._scheduler = scheduler@@ -121,30 +108,28 @@ class OnlineTrialRunner:return self._running_trialsdef step(self, data_sample=None, prediction_trial_tuple=None):- """Schedule up to max_live_model_num trials to run.+ """Schedule one trial to run each time it is called.Args:- data_sample- prediction_trial_tuple-- NOTE:- It consists of the following several parts:- * Update model:- 0. Update running trials using observations received.- * Tests for Champion:- 1. Test for champion (BetterThan test, and WorseThan test)- 1.1 BetterThan test- 1.2 WorseThan test: a trial may be removed if WroseThan test is triggered- * Online Scheduling:- 2. Report results to the searcher and scheduler (the scheduler will return a decision about- the status of the running trials).- 3. Pause or stop a trial according to the scheduler's decision.- Add trial into the OnlineTrialRunner if there are opening slots.-- TODO:- add documentation about the Args+ data_sample: One data example.+ prediction_trial_tuple: A list of information containing+ (prediction_made, prediction_trial)."""- # ***********Update running trials with observation***************************+ # TODO: Will remove prediction_trial_tuple.+ # NOTE: This function consists of the following several parts:+ # * Update model:+ # 0. Update running trials using observations received.+ # * Tests for Champion:+ # 1. Test for champion (BetterThan test, and WorseThan test)+ # 1.1 BetterThan test+ # 1.2 WorseThan test: a trial may be removed if WroseThan test is triggered+ # * Online Scheduling:+ # 2. Report results to the searcher and scheduler (the scheduler will return a decision about+ # the status of the running trials).+ # 3. Pause or stop a trial according to the scheduler's decision.+ # Add a trial into the OnlineTrialRunner if there are opening slots.++ # ***********Update running trials with observation*******************if data_sample is not None:self._total_steps += 1prediction_made, prediction_trial = (@@ -385,16 +370,13 @@ class OnlineTrialRunner:def add_trial(self, new_trial):"""Add a new trial to this TrialRunner.-Trials may be added at any time.Args:- trial (Trial): Trial to queue.-- NOTE:- Only add the new trial when it does not exist (according to the trial_id, which is- the signature of the trail) in self._trials.+ new_trial (Trial): Trial to queue."""+ # Only add the new trial when it does not exist (according to the trial_id, which is+ # the signature of the trail) in self._trials.for trial in self._trials:if trial.trial_id == new_trial.trial_id:trial.set_checked_under_current_champion(True)@@ -409,8 +391,8 @@ class OnlineTrialRunner:self._scheduler.on_trial_add(self, new_trial)def stop_trial(self, trial):- """Stop a trial: set the status of a trial to be Trial.TERMINATED and perform- other subsequent operations.+ """Stop a trial: set the status of a trial to be+ Trial.TERMINATED and perform other subsequent operations."""if trial.status in [Trial.ERROR, Trial.TERMINATED]:return@@ -428,8 +410,8 @@ class OnlineTrialRunner:self._running_trials.remove(trial)def pause_trial(self, trial):- """Pause a trial: set the status of a trial to be Trial.PAUSED and perform other- subsequent operations.+ """Pause a trial: set the status of a trial to be Trial.PAUSED+ and perform other subsequent operations."""if trial.status in [Trial.ERROR, Trial.TERMINATED]:return@@ -450,8 +432,8 @@ class OnlineTrialRunner:self._running_trials.remove(trial)def run_trial(self, trial):- """Run a trial: set the status of a trial to be Trial.RUNNING and perform other- subsequent operations.+ """Run a trial: set the status of a trial to be Trial.RUNNING+ and perform other subsequent operations."""if trial.status in [Trial.ERROR, Trial.TERMINATED]:return@@ -460,8 +442,8 @@ class OnlineTrialRunner:self._running_trials.add(trial)def _better_than_champion_test(self, trial_to_test):- """Test whether there is a config in the existing trials that is better than- the current champion config.+ """Test whether there is a config in the existing trials that+ is better than the current champion config.Returns:A bool indicating whether a new champion is found.diff --git a/flaml/scheduler/online_scheduler.py b/flaml/scheduler/online_scheduler.pyindex 1fe8ae829..55f2563fe 100644--- a/flaml/scheduler/online_scheduler.py+++ b/flaml/scheduler/online_scheduler.py@@ -8,30 +8,18 @@ logger = logging.getLogger(__name__)class OnlineScheduler(TrialScheduler):- """Implementation of the OnlineFIFOSchedulers.-- Methods:- * on_trial_result(trial_runner, trial, result):- Report result and return a decision on the trial's status.- * choose_trial_to_run(trial_runner):- Decide which trial to run next.- """+ """Class for the most basic OnlineScheduler."""def on_trial_result(self, trial_runner, trial: Trial, result: Dict):- """Report result and return a decision on the trial's status.-- Always keep a trial running (return status TrialScheduler.CONTINUE).- """+ """Report result and return a decision on the trial's status."""+ # Always keep a trial running (return status TrialScheduler.CONTINUE).return TrialScheduler.CONTINUEdef choose_trial_to_run(self, trial_runner) -> Trial:- """Decide which trial to run next.-- Trial prioritrization according to the status:- PENDING (trials that have not been tried) > PAUSED (trials that have been ran).-- For trials with the same status, it chooses the ones with smaller resource lease.- """+ """Decide which trial to run next."""+ # Trial prioritrization according to the status:+ # PENDING (trials that have not been tried) > PAUSED (trials that have been ran).+ # For trials with the same status, it chooses the ones with smaller resource lease.for trial in trial_runner.get_trials():if trial.status == Trial.PENDING:return trial@@ -50,31 +38,23 @@ class OnlineScheduler(TrialScheduler):class OnlineSuccessiveDoublingScheduler(OnlineScheduler):- """Implementation of the OnlineSuccessiveDoublingScheduler.-- Methods:- * on_trial_result(trial_runner, trial, result):- Report result and return a decision on the trial's status.- * choose_trial_to_run(trial_runner):- Decide which trial to run next.- """+ """class for the OnlineSuccessiveDoublingScheduler algorithm."""def __init__(self, increase_factor: float = 2.0):- """+ """Constructor.+Args:- increase_factor (float): a multiplicative factor used to increase resource lease.- The default value is 2.0+ increase_factor: A float of multiplicative factor+ used to increase resource lease. Default is 2.0."""super().__init__()self._increase_factor = increase_factordef on_trial_result(self, trial_runner, trial: Trial, result: Dict):- """Report result and return a decision on the trial's status.-- 1. Returns TrialScheduler.CONTINUE (i.e., keep the trial running),- if the resource consumed has not reached the current resource_lease.s.- 2. otherwise double the current resource lease and return TrialScheduler.PAUSE.- """+ """Report result and return a decision on the trial's status."""+ # 1. Returns TrialScheduler.CONTINUE (i.e., keep the trial running),+ # if the resource consumed has not reached the current resource_lease.s.+ # 2. otherwise double the current resource lease and return TrialScheduler.PAUSE.if trial.result is None or trial.result.resource_used < trial.resource_lease:return TrialScheduler.CONTINUEelse:@@ -89,20 +69,14 @@ class OnlineSuccessiveDoublingScheduler(OnlineScheduler):class ChaChaScheduler(OnlineSuccessiveDoublingScheduler):- """Keep the top performing learners running.-- Methods:- * on_trial_result(trial_runner, trial, result):- Report result and return a decision on the trial's status.- * choose_trial_to_run(trial_runner):- Decide which trial to run next.- """+ """class for the ChaChaScheduler algorithm."""def __init__(self, increase_factor: float = 2.0, **kwargs):- """+ """Constructor.+Args:- increase_factor: a multiplicative factor used to increase resource lease.- The default value is 2.0.+ increase_factor: A float of multiplicative factor+ used to increase resource lease. Default is 2.0."""super().__init__(increase_factor)self._keep_champion = kwargs.get("keep_champion", True)@@ -112,10 +86,8 @@ class ChaChaScheduler(OnlineSuccessiveDoublingScheduler):logger.info("Using chacha scheduler with config %s", kwargs)def on_trial_result(self, trial_runner, trial: Trial, result: Dict):- """Report result and return a decision on the trial's status.-- Make a decision according to: SuccessiveDoubling + champion check + performance check.- """+ """Report result and return a decision on the trial's status."""+ # Make a decision according to: SuccessiveDoubling + champion check + performance check.# Doubling scheduler makes a decisiondecision = super().on_trial_result(trial_runner, trial, result)# ***********Check whether the trial has been paused since a new champion is promoted**diff --git a/flaml/searcher/online_searcher.py b/flaml/searcher/online_searcher.pyindex 62e3261a1..536c0f2ed 100644--- a/flaml/searcher/online_searcher.py+++ b/flaml/searcher/online_searcher.py@@ -11,14 +11,7 @@ logger = logging.getLogger(__name__)class BaseSearcher:- """Implementation of the BaseSearcher.-- Methods:- * set_search_properties(metric, mode, config)- * next_trial()- * on_trial_result(trial_id, result)- * on_trial_complete()- """+ """Abstract class for an online searcher."""def __init__(self,@@ -52,26 +45,19 @@ class BaseSearcher:class ChampionFrontierSearcher(BaseSearcher):"""The ChampionFrontierSearcher class.- Methods:- * (metric, mode, config):- Generate a list of new challengers, and add them to the _challenger_list.- * next_trial():- Pop a trial from the _challenger_list.- * on_trial_result(trial_id, result):- Doing nothing.- * on_trial_complete()- Doing nothing.-- NOTE:- This class serves the role of ConfigOralce.- Every time we create an online trial, we generate a searcher_trial_id.- At the same time, we also record the trial_id of the VW trial.- Note that the trial_id is a unique signature of the configuraiton.- So if two VWTrials are associated with the same config, they will have the same trial_id- (although not the same searcher_trial_id).- searcher_trial_id will be used in suggest().+ NOTE about the correspondence about this code and the research paper:+ [ChaCha for Online AutoML](https://arxiv.org/pdf/2106.04815.pdf)+ This class serves the role of ConfigOralce as described in the paper."""+ # **************************More notes***************************+ # Every time we create an online trial, we generate a searcher_trial_id.+ # At the same time, we also record the trial_id of the VW trial.+ # Note that the trial_id is a unique signature of the configuration.+ # So if two VWTrials are associated with the same config, they will have the same trial_id+ # (although not the same searcher_trial_id).+ # searcher_trial_id will be used in suggest().+# ****the following constants are used when generating new challengers in# the _query_config_oracle function# how many item to add when doing the expansion@@ -112,12 +98,14 @@ class ChampionFrontierSearcher(BaseSearcher):"""Constructor.Args:- init_config: dict.- space: dict.- metric: str.- mode: str.- random_seed: int.- online_trial_args: dict.+ init_config: A dictionary of initial configuration.+ space: A dictionary to specify the search space.+ metric: A string of the metric name to optimize for.+ mode: A string in ['min', 'max'] to specify the objective as+ minimization or maximization.+ random_seed: An integer of the random seed.+ online_trial_args: A dictionary to specify the online trial+ arguments for experimental purpose.nonpoly_searcher_name: A string to specify the search algorithmfor nonpoly hyperparameters."""@@ -154,7 +142,7 @@ class ChampionFrontierSearcher(BaseSearcher):setting: Optional[Dict] = {},init_call: Optional[bool] = False,):- """Construct search space with given config, and setup the search."""+ """Construct search space with the given config, and setup the search."""super().set_search_properties(metric, mode, config)# *********Use ConfigOralce (i.e, self._generate_new_space to generate list of new challengers)logger.info("setting %s", setting)