Tune Internals
Contents
Tune Internals#
RayTrialExecutor#
- class ray.tune.execution.ray_trial_executor.RayTrialExecutor(resource_manager: Optional[ray.air.execution.resources.resource_manager.ResourceManager] = None, reuse_actors: bool = False, result_buffer_length: Optional[int] = None, refresh_period: Optional[float] = None, chdir_to_trial_dir: bool = False)[source]#
An implementation of TrialExecutor based on Ray.
DeveloperAPI: This API may change across minor Ray releases.
- set_status(trial: ray.tune.experiment.trial.Trial, status: str) None [source]#
Sets status and checkpoints metadata if needed.
Only checkpoints metadata if trial status is a terminal condition. PENDING, PAUSED, and RUNNING switches have checkpoints taken care of in the TrialRunner.
- Parameters
trial β Trial to checkpoint.
status β Status to set trial to.
- get_checkpoints() Dict[str, str] [source]#
Returns a copy of mapping of the trial ID to pickled metadata.
- get_ready_trial() Optional[ray.tune.experiment.trial.Trial] [source]#
Get a trial whose resources are ready and that thus can be started.
Can also return None if no trial is available.
- Returns
Trial object or None.
- start_trial(trial: ray.tune.experiment.trial.Trial) bool [source]#
Starts the trial.
Will not return resources if trial repeatedly fails on start.
- Parameters
trial β Trial to be started.
- Returns
- True if the remote runner has been started. False if trial was
not started (e.g. because of lacking resources/pending PG).
- stop_trial(trial: ray.tune.experiment.trial.Trial, error: bool = False, exc: Optional[Union[ray.tune.error.TuneError, ray.exceptions.RayTaskError]] = None) None [source]#
Stops the trial, releasing held resources and removing futures related to this trial from the execution queue.
- Parameters
trial β Trial to stop.
error β Whether to mark this trial as terminated in error. The trial status will be set to either
Trial.ERROR
orTrial.TERMINATED
based on this. Defaults to False.exc β Optional exception to log (as a reason for stopping). Defaults to None.
- continue_training(trial: ray.tune.experiment.trial.Trial) None [source]#
Continues the training of this trial.
- pause_trial(trial: ray.tune.experiment.trial.Trial, should_checkpoint: bool = True) None [source]#
Pauses the trial, releasing resources (specifically GPUs)
We do this by: 1. Checkpoint the trial (if
should_checkpoint
) in memory to allow us to resume from this state in the future. We may not always want to checkpoint, if we know that the checkpoint will not be used. 2. Stop the trial and release resources, seeRayTrialExecutor.stop_trial
above 3. Set the trial status toTrial.PAUSED
, which is similar toTrial.TERMINATED
, except we have the intention of resuming the trial.- Parameters
trial β Trial to pause.
should_checkpoint β Whether to save an in-memory checkpoint before stopping.
- reset_trial(trial: ray.tune.experiment.trial.Trial, new_config: Dict, new_experiment_tag: str, logger_creator: Optional[Callable[[Dict], ray.tune.Logger]] = None) bool [source]#
Tries to invoke
Trainable.reset()
to reset trial.- Parameters
trial β Trial to be reset.
new_config β New configuration for Trial trainable.
new_experiment_tag β New experiment name for trial.
logger_creator β Function that instantiates a logger on the actor process.
- Returns
True if
reset_config
is successful else False.
- has_resources_for_trial(trial: ray.tune.experiment.trial.Trial) bool [source]#
Returns whether there are resources available for this trial.
This will return True as long as we didnβt reach the maximum number of pending trials. It will also return True if the trial placement group is already staged.
- Parameters
trial β Trial object which should be scheduled.
- Returns
boolean
- save(trial: ray.tune.experiment.trial.Trial, storage: ray.air._internal.checkpoint_manager.CheckpointStorage = CheckpointStorage.PERSISTENT, result: Optional[Dict] = None) ray.air._internal.checkpoint_manager._TrackedCheckpoint [source]#
Saves the trialβs state to a checkpoint asynchronously.
- Parameters
trial β The trial to be saved.
storage β Where to store the checkpoint. Defaults to PERSISTENT.
result β The state of this trial as a dictionary to be saved. If result is None, the trialβs last result will be used.
- Returns
Checkpoint object, or None if an Exception occurs.
- restore(trial: ray.tune.experiment.trial.Trial) None [source]#
Restores training state from a given model checkpoint.
- Parameters
trial β The trial to be restored.
- Raises
RuntimeError β This error is raised if no runner is found.
AbortTrialExecution β This error is raised if the trial is ineligible for restoration, given the Tune input arguments.
- export_trial_if_needed(trial: ray.tune.experiment.trial.Trial) Dict [source]#
Exports model of this trial based on trial.export_formats.
- Returns
A dict that maps ExportFormats to successfully exported models.
- get_next_executor_event(live_trials: Set[ray.tune.experiment.trial.Trial], next_trial_exists: bool) ray.tune.execution.ray_trial_executor._ExecutorEvent [source]#
Get the next executor event to be processed in TrialRunner.
In case there are multiple events available for handling, the next event is determined by the following priority: 1. if there is
next_trial_exists
, and if there is cached resources to use, PG_READY is emitted. 2. if there isnext_trial_exists
and there is no cached resources to use, wait on pg future and randomized other futures. If multiple futures are ready, pg future will take priority to be handled first. 3. if there is nonext_trial_exists
, wait on just randomized other futures.An example of #3 would be synchronous hyperband. Although there are pgs ready, the scheduler is holding back scheduling new trials since the whole band of trials is waiting for the slowest trial to finish. In this case, we prioritize handling training result to avoid deadlock situation.
This is a blocking wait with a timeout (specified with env var). The reason for the timeout is we still want to print status info periodically in TrialRunner for better user experience.
The handle of
ExecutorEvent.STOP_RESULT
is purely internal to RayTrialExecutor itself. All the other future results are handled by TrialRunner.In the future we may want to do most of the handle of
ExecutorEvent.RESTORE_RESULT
andSAVING_RESULT
in RayTrialExecutor itself and only notify TrialRunner to invoke corresponding callbacks. This view is more consistent with our goal of TrialRunner responsible for external facing Trial state transition, while RayTrialExecutor responsible for internal facing transitions, namely,is_saving
,is_restoring
etc.Also you may notice that the boundary between RayTrialExecutor and PlacementGroupManager right now is really blurry. This will be improved once we move to an ActorPool abstraction.
next_trial_exists
means that there is a trial to run - prioritize returning PG_READY in this case.
TrialRunner#
- class ray.tune.execution.trial_runner.TrialRunner(search_alg: Optional[ray.tune.search.search_algorithm.SearchAlgorithm] = None, scheduler: Optional[ray.tune.schedulers.trial_scheduler.TrialScheduler] = None, local_checkpoint_dir: Optional[str] = None, sync_config: Optional[ray.tune.syncer.SyncConfig] = None, experiment_dir_name: Optional[str] = None, stopper: Optional[ray.tune.stopper.stopper.Stopper] = None, resume: Union[str, bool] = False, server_port: Optional[int] = None, fail_fast: bool = False, checkpoint_period: Optional[Union[str, int]] = None, trial_executor: Optional[ray.tune.execution.ray_trial_executor.RayTrialExecutor] = None, callbacks: Optional[List[ray.tune.callback.Callback]] = None, metric: Optional[str] = None, trial_checkpoint_config: Optional[ray.air.config.CheckpointConfig] = None, driver_sync_trial_checkpoints: bool = False)[source]#
A TrialRunner implements the event loop for scheduling trials on Ray.
The main job of TrialRunner is scheduling trials to efficiently use cluster resources, without overloading the cluster.
While Ray itself provides resource management for tasks and actors, this is not sufficient when scheduling trials that may instantiate multiple actors. This is because if insufficient resources are available, concurrent trials could deadlock waiting for new resources to become available. Furthermore, oversubscribing the cluster could degrade training performance, leading to misleading benchmark results.
- Parameters
search_alg β SearchAlgorithm for generating Trial objects.
scheduler β Defaults to FIFOScheduler.
local_checkpoint_dir β Path where global experiment state checkpoints are saved and restored from.
sync_config β See
SyncConfig
. Within sync config, theupload_dir
specifies cloud storage, and experiment state checkpoints will be synced to theremote_checkpoint_dir
:{sync_config.upload_dir}/{experiment_name}
.experiment_dir_name β Experiment directory name. See
Experiment
.stopper β Custom class for stopping whole experiments. See
Stopper
.resume β see
tune.py:run
.server_port β Port number for launching TuneServer.
fail_fast β Finishes as soon as a trial fails if True. If fail_fast=βraiseβ provided, Tune will automatically raise the exception received by the Trainable. fail_fast=βraiseβ can easily leak resources and should be used with caution.
checkpoint_period β Trial runner checkpoint periodicity in seconds. Defaults to
"auto"
, which adjusts checkpointing time so that at most 5% of the time is spent on writing checkpoints.trial_executor β Defaults to RayTrialExecutor.
callbacks β List of callbacks that will be called at different times in the training loop. Must be instances of the
ray.tune.execution.trial_runner.Callback
class.metric β Metric used to check received results. If a result is reported without this metric, an error will be raised. The error can be omitted by not providing a metric or by setting the env variable
TUNE_DISABLE_STRICT_METRIC_CHECKING=0
DeveloperAPI: This API may change across minor Ray releases.
Trial#
- class ray.tune.experiment.trial.Trial(trainable_name: str, *, config: Optional[Dict] = None, trial_id: Optional[str] = None, local_dir: Optional[str] = '/home/docs/ray_results', evaluated_params: Optional[Dict] = None, experiment_tag: str = '', resources: Optional[ray.tune.resources.Resources] = None, placement_group_factory: Optional[ray.tune.execution.placement_groups.PlacementGroupFactory] = None, stopping_criterion: Optional[Dict[str, float]] = None, experiment_dir_name: Optional[str] = None, sync_config: Optional[ray.tune.syncer.SyncConfig] = None, checkpoint_config: Optional[ray.air.config.CheckpointConfig] = None, export_formats: Optional[List[str]] = None, restore_path: Optional[str] = None, trial_name_creator: Optional[Callable[[ray.tune.experiment.trial.Trial], str]] = None, trial_dirname_creator: Optional[Callable[[ray.tune.experiment.trial.Trial], str]] = None, log_to_file: Union[str, None, Tuple[Optional[str], Optional[str]]] = None, max_failures: int = 0, stub: bool = False, _setup_default_resource: bool = True)[source]#
A trial object holds the state for one model training run.
Trials are themselves managed by the TrialRunner class, which implements the event loop for submitting trial runs to a Ray cluster.
Trials start in the PENDING state, and transition to RUNNING once started. On error it transitions to ERROR, otherwise TERMINATED on success.
There are resources allocated to each trial. These should be specified using
PlacementGroupFactory
.- trainable_name#
Name of the trainable object to be executed.
- config#
Provided configuration dictionary with evaluated params.
- trial_id#
Unique identifier for the trial.
- local_dir#
local_dir
as passed toair.RunConfig()
joined with the name of the experiment.
- logdir#
Directory where the trial logs are saved.
- relative_logdir#
Same as
logdir
, but relative to the parent of thelocal_dir
(equal tolocal_dir
argument passed toair.RunConfig()
).
- evaluated_params#
Evaluated parameters by search algorithm,
- experiment_tag#
Identifying trial name to show in the console
- status#
One of PENDING, RUNNING, PAUSED, TERMINATED, ERROR/
- error_file#
Path to the errors that this trial has raised.
DeveloperAPI: This API may change across minor Ray releases.
Callbacks#
- class ray.tune.callback.Callback[source]#
Tune base callback that can be extended and passed to a
TrialRunner
Tune callbacks are called from within the
TrialRunner
class. There are several hooks that can be used, all of which are found in the submethod definitions of this base class.The parameters passed to the
**info
dict vary between hooks. The parameters passed are described in the docstrings of the methods.This example will print a metric each time a result is received:
from ray import air, tune from ray.tune import Callback class MyCallback(Callback): def on_trial_result(self, iteration, trials, trial, result, **info): print(f"Got result: {result['metric']}") def train(config): for i in range(10): tune.report(metric=i) tuner = tune.Tuner( train, run_config=air.RunConfig( callbacks=[MyCallback()] ) ) tuner.fit()
PublicAPI (beta): This API is in beta and may change before becoming stable.
- setup(stop: Optional[Stopper] = None, num_samples: Optional[int] = None, total_num_samples: Optional[int] = None, **info)[source]#
Called once at the very beginning of training.
Any Callback setup should be added here (setting environment variables, etc.)
- Parameters
stop β Stopping criteria. If
time_budget_s
was passed toair.RunConfig
, aTimeoutStopper
will be passed here, either by itself or as a part of aCombinedStopper
.num_samples β Number of times to sample from the hyperparameter space. Defaults to 1. If
grid_search
is provided as an argument, the grid will be repeatednum_samples
of times. If this is -1, (virtually) infinite samples are generated until a stopping condition is met.total_num_samples β Total number of samples factoring in grid search samplers.
**info β Kwargs dict for forward compatibility.
- on_step_begin(iteration: int, trials: List[Trial], **info)[source]#
Called at the start of each tuning loop step.
- Parameters
iteration β Number of iterations of the tuning loop.
trials β List of trials.
**info β Kwargs dict for forward compatibility.
- on_step_end(iteration: int, trials: List[Trial], **info)[source]#
Called at the end of each tuning loop step.
The iteration counter is increased before this hook is called.
- Parameters
iteration β Number of iterations of the tuning loop.
trials β List of trials.
**info β Kwargs dict for forward compatibility.
- on_trial_start(iteration: int, trials: List[Trial], trial: Trial, **info)[source]#
Called after starting a trial instance.
- Parameters
iteration β Number of iterations of the tuning loop.
trials β List of trials.
trial β Trial that just has been started.
**info β Kwargs dict for forward compatibility.
- on_trial_restore(iteration: int, trials: List[Trial], trial: Trial, **info)[source]#
Called after restoring a trial instance.
- Parameters
iteration β Number of iterations of the tuning loop.
trials β List of trials.
trial β Trial that just has been restored.
**info β Kwargs dict for forward compatibility.
- on_trial_save(iteration: int, trials: List[Trial], trial: Trial, **info)[source]#
Called after receiving a checkpoint from a trial.
- Parameters
iteration β Number of iterations of the tuning loop.
trials β List of trials.
trial β Trial that just saved a checkpoint.
**info β Kwargs dict for forward compatibility.
- on_trial_result(iteration: int, trials: List[Trial], trial: Trial, result: Dict, **info)[source]#
Called after receiving a result from a trial.
The search algorithm and scheduler are notified before this hook is called.
- Parameters
iteration β Number of iterations of the tuning loop.
trials β List of trials.
trial β Trial that just sent a result.
result β Result that the trial sent.
**info β Kwargs dict for forward compatibility.
- on_trial_complete(iteration: int, trials: List[Trial], trial: Trial, **info)[source]#
Called after a trial instance completed.
The search algorithm and scheduler are notified before this hook is called.
- Parameters
iteration β Number of iterations of the tuning loop.
trials β List of trials.
trial β Trial that just has been completed.
**info β Kwargs dict for forward compatibility.
- on_trial_error(iteration: int, trials: List[Trial], trial: Trial, **info)[source]#
Called after a trial instance failed (errored).
The search algorithm and scheduler are notified before this hook is called.
- Parameters
iteration β Number of iterations of the tuning loop.
trials β List of trials.
trial β Trial that just has errored.
**info β Kwargs dict for forward compatibility.
- on_checkpoint(iteration: int, trials: List[Trial], trial: Trial, checkpoint: _TrackedCheckpoint, **info)[source]#
Called after a trial saved a checkpoint with Tune.
- Parameters
iteration β Number of iterations of the tuning loop.
trials β List of trials.
trial β Trial that just has errored.
checkpoint β Checkpoint object that has been saved by the trial.
**info β Kwargs dict for forward compatibility.
- on_experiment_end(trials: List[Trial], **info)[source]#
Called after experiment is over and all trials have concluded.
- Parameters
trials β List of trials.
**info β Kwargs dict for forward compatibility.
- get_state() Optional[Dict] [source]#
Get the state of the callback.
This method should be implemented by subclasses to return a dictionary representation of the objectβs current state.
- Returns
- State of the callback. Should be
None
if the callback does not have any state to save (this is the default).
- State of the callback. Should be
- Return type
state
PlacementGroupFactory#
- class ray.tune.execution.placement_groups.PlacementGroupFactory(bundles: List[Dict[str, Union[int, float]]], strategy: str = 'PACK', *args, **kwargs)[source]#
Wrapper class that creates placement groups for trials.
This function should be used to define resource requests for Ray Tune trials. It holds the parameters to create placement groups. At a minimum, this will hold at least one bundle specifying the resource requirements for each trial:
from ray import tune tuner = tune.Tuner( tune.with_resources( train, resources=tune.PlacementGroupFactory([ {"CPU": 1, "GPU": 0.5, "custom_resource": 2} ]) ) ) tuner.fit()
If the trial itself schedules further remote workers, the resource requirements should be specified in additional bundles. You can also pass the placement strategy for these bundles, e.g. to enforce co-located placement:
from ray import tune tuner = tune.Tuner( tune.with_resources( train, resources=tune.PlacementGroupFactory([ {"CPU": 1, "GPU": 0.5, "custom_resource": 2}, {"CPU": 2}, {"CPU": 2}, ], strategy="PACK") ) ) tuner.fit()
The example above will reserve 1 CPU, 0.5 GPUs and 2 custom_resources for the trainable itself, and reserve another 2 bundles of 2 CPUs each. The trial will only start when all these resources are available. This could be used e.g. if you had one learner running in the main trainable that schedules two remote workers that need access to 2 CPUs each.
If the trainable itself doesnβt require resources. You can specify it as:
from ray import tune tuner = tune.Tuner( tune.with_resources( train, resources=tune.PlacementGroupFactory([ {}, {"CPU": 2}, {"CPU": 2}, ], strategy="PACK") ) ) tuner.fit()
- Parameters
bundles β A list of bundles which represent the resources requirements.
strategy β
The strategy to create the placement group.
βPACKβ: Packs Bundles into as few nodes as possible.
βSPREADβ: Places Bundles across distinct nodes as even as possible.
βSTRICT_PACKβ: Packs Bundles into one node. The group is not allowed to span multiple nodes.
βSTRICT_SPREADβ: Packs Bundles across distinct nodes.
*args β Passed to the call of
placement_group()
**kwargs β Passed to the call of
placement_group()
PublicAPI (beta): This API is in beta and may change before becoming stable.
Registry#
- ray.tune.register_trainable(name: str, trainable: Union[Callable, Type], warn: bool = True)[source]#
Register a trainable function or class.
This enables a class or function to be accessed on every Ray process in the cluster.
- Parameters
name β Name to register.
trainable β Function or tune.Trainable class. Functions must take (config, status_reporter) as arguments and will be automatically converted into a class during registration.
DeveloperAPI: This API may change across minor Ray releases.
- ray.tune.register_env(name: str, env_creator: Callable)[source]#
Register a custom environment for use with RLlib.
This enables the environment to be accessed on every Ray process in the cluster.
- Parameters
name β Name to register.
env_creator β Callable that creates an env.
DeveloperAPI: This API may change across minor Ray releases.