[tune] Make the logging of the function API consistent and predictable (#4011)

## What do these changes do?

This is a re-implementation of the `FunctionRunner` which enforces some synchronicity between the thread running the training function and the thread running the Trainable which logs results. The main purpose is to make logging consistent across APIs in anticipation of a new function API which will be generator based (through `yield` statements). Without these changes, it will be impossible for the (possibly soon to be) deprecated reporter based API to behave the same as the generator based API.

This new implementation provides additional guarantees to prevent results from being dropped. This makes the logging behavior more intuitive and consistent with how results are handled in custom subclasses of Trainable.

New guarantees for the tune function API:

- Every reported result, i.e., `reporter(**kwargs)` calls, is forwarded to the appropriate loggers instead of being dropped if not enough time has elapsed since the last results.
- The wrapped function only runs if the `FunctionRunner` expects a result, i.e., when `FunctionRunner._train()` has been called. This removes the possibility that a result will be generated by the function but never logged.
- The wrapped function is not called until the first `_train()` call. Currently, the wrapped function is started during the setup phase which could result in dropped results if the trial is cancelled between `_setup()` and the first `_train()` call.
- Exceptions raised by the wrapped function won't be propagated until all results are logged to prevent dropped results.
- The thread running the wrapped function is explicitly stopped when the `FunctionRunner` is stopped with `_stop()`.
- If the wrapped function terminates without reporting `done=True`, a duplicate result with `{"done": True}`, is reported to explicitly terminate the trial, and components will be notified with a duplicate of the last reported result, but this duplicate will not be logged.

## Related issue number

Closes #3956.
#3949
#3834
This commit is contained in:
gehring
2019-03-18 22:14:26 -04:00
committed by Richard Liaw
parent edb063c3c8
commit 7c3274e65b
5 changed files with 385 additions and 191 deletions
+182 -71
View File
@@ -3,15 +3,24 @@ from __future__ import division
from __future__ import print_function
import logging
import sys
import time
import threading
from six.moves import queue
from ray.tune import TuneError
from ray.tune.trainable import Trainable
from ray.tune.result import TIMESTEPS_TOTAL, TRAINING_ITERATION
from ray.tune.result import TIME_THIS_ITER_S
logger = logging.getLogger(__name__)
# Time between FunctionRunner checks when fetching
# new results after signaling the reporter to continue
RESULT_FETCH_TIMEOUT = 0.2
ERROR_REPORT_TIMEOUT = 10
ERROR_FETCH_TIMEOUT = 1
class StatusReporter(object):
"""Object passed into your function that you can report status through.
@@ -19,16 +28,13 @@ class StatusReporter(object):
Example:
>>> def trainable_function(config, reporter):
>>> assert isinstance(reporter, StatusReporter)
>>> reporter(timesteps_total=1)
>>> reporter(timesteps_this_iter=1)
"""
def __init__(self):
self._latest_result = None
self._last_result = None
self._lock = threading.Lock()
self._error = None
self._done = False
self._iteration = 0
def __init__(self, result_queue, continue_semaphore):
self._queue = result_queue
self._last_report_time = None
self._continue_semaphore = continue_semaphore
def __call__(self, **kwargs):
"""Report updated training status.
@@ -41,82 +47,101 @@ class StatusReporter(object):
Example:
>>> reporter(mean_accuracy=1, training_iteration=4)
>>> reporter(mean_accuracy=1, training_iteration=4, done=True)
Raises:
StopIteration: A StopIteration exception is raised if the trial has
been signaled to stop.
"""
with self._lock:
self._latest_result = self._last_result = kwargs.copy()
self._iteration += 1
assert self._last_report_time is not None, (
"StatusReporter._start() must be called before the first "
"report __call__ is made to ensure correct runtime metrics.")
def _get_and_clear_status(self):
if self._error:
raise TuneError("Error running trial: " + str(self._error))
if self._done and not self._latest_result:
if not self._last_result:
raise TuneError("Trial finished without reporting result!")
logger.warning("Trial detected as completed; re-reporting "
"last result. To avoid this, include done=True "
"upon the last reporter call.")
self._last_result.update(done=True)
self._last_result.setdefault(TRAINING_ITERATION, self._iteration)
return self._last_result
with self._lock:
res = self._latest_result
self._latest_result = None
if res:
res.setdefault(TRAINING_ITERATION, self._iteration)
return res
# time per iteration is recorded directly in the reporter to ensure
# any delays in logging results aren't counted
report_time = time.time()
if TIME_THIS_ITER_S not in kwargs:
kwargs[TIME_THIS_ITER_S] = report_time - self._last_report_time
self._last_report_time = report_time
def _stop(self):
self._error = "Agent stopped"
# add results to a thread-safe queue
self._queue.put(kwargs.copy(), block=True)
# This blocks until notification from the FunctionRunner that the last
# result has been returned to Tune and that the function is safe to
# resume training.
self._continue_semaphore.acquire()
DEFAULT_CONFIG = {
# batch results to at least this granularity
"script_min_iter_time_s": 1,
}
def _start(self):
self._last_report_time = time.time()
class _RunnerThread(threading.Thread):
"""Supervisor thread that runs your script."""
def __init__(self, entrypoint, config, status_reporter):
self._entrypoint = entrypoint
self._entrypoint_args = [config, status_reporter]
self._status_reporter = status_reporter
def __init__(self, entrypoint, error_queue):
threading.Thread.__init__(self)
self._entrypoint = entrypoint
self._error_queue = error_queue
self.daemon = True
def run(self):
try:
self._entrypoint(*self._entrypoint_args)
self._entrypoint()
except StopIteration:
logger.debug(
("Thread runner raised StopIteration. Interperting it as a "
"signal to terminate the thread without error."))
except Exception as e:
self._status_reporter._error = e
logger.exception("Runner Thread raised error.")
try:
# report the error but avoid indefinite blocking which would
# prevent the exception from being propagated in the unlikely
# case that something went terribly wrong
err_type, err_value, err_tb = sys.exc_info()
err_tb = err_tb.format_exc()
self._error_queue.put(
(err_type, err_value, err_tb),
block=True,
timeout=ERROR_REPORT_TIMEOUT)
except queue.Full:
logger.critical(
("Runner Thread was unable to report error to main "
"function runner thread. This means a previous error "
"was not processed. This should never happen."))
raise e
finally:
self._status_reporter._done = True
class FunctionRunner(Trainable):
"""Trainable that runs a user function returning training results.
"""Trainable that runs a user function reporting results.
This mode of execution does not support checkpoint/restore."""
_name = "func"
_default_config = DEFAULT_CONFIG
def _setup(self, config):
entrypoint = self._trainable_func()
self._status_reporter = StatusReporter()
scrubbed_config = config.copy()
for k in self._default_config:
if k in scrubbed_config:
del scrubbed_config[k]
self._runner = _RunnerThread(entrypoint, scrubbed_config,
self._status_reporter)
self._start_time = time.time()
self._last_reported_timestep = 0
self._runner.start()
# Semaphore for notifying the reporter to continue with the computation
# and to generate the next result.
self._continue_semaphore = threading.Semaphore(0)
# Queue for passing results between threads
self._results_queue = queue.Queue(1)
# Queue for passing errors back from the thread runner. The error queue
# has a max size of one to prevent stacking error and force error
# reporting to block until finished.
self._error_queue = queue.Queue(1)
self._status_reporter = StatusReporter(self._results_queue,
self._continue_semaphore)
self._last_result = {}
config = config.copy()
def entrypoint():
return self._trainable_func(config, self._status_reporter)
# the runner thread is not started until the first call to _train
self._runner = _RunnerThread(entrypoint, self._error_queue)
def _trainable_func(self):
"""Subclasses can override this to set the trainable func."""
@@ -124,22 +149,108 @@ class FunctionRunner(Trainable):
raise NotImplementedError
def _train(self):
time.sleep(
self.config.get("script_min_iter_time_s",
self._default_config["script_min_iter_time_s"]))
result = self._status_reporter._get_and_clear_status()
while result is None:
time.sleep(1)
result = self._status_reporter._get_and_clear_status()
"""Implements train() for a Function API.
curr_ts_total = result.get(TIMESTEPS_TOTAL)
if curr_ts_total is not None:
result.update(
timesteps_this_iter=(
curr_ts_total - self._last_reported_timestep))
self._last_reported_timestep = curr_ts_total
If the RunnerThread finishes without reporting "done",
Tune will automatically provide a magic keyword __duplicate__
along with a result with "done=True". The TrialRunner will handle the
result accordingly (see tune/trial_runner.py).
"""
if self._runner.is_alive():
# if started and alive, inform the reporter to continue and
# generate the next result
self._continue_semaphore.release()
else:
# if not alive, try to start
self._status_reporter._start()
try:
self._runner.start()
except RuntimeError:
# If this is reached, it means the thread was started and is
# now done or has raised an exception.
pass
result = None
while result is None and self._runner.is_alive():
# fetch the next produced result
try:
result = self._results_queue.get(
block=True, timeout=RESULT_FETCH_TIMEOUT)
except queue.Empty:
pass
# if no result were found, then the runner must no longer be alive
if result is None:
# Try one last time to fetch results in case results were reported
# in between the time of the last check and the termination of the
# thread runner.
try:
result = self._results_queue.get(block=False)
except queue.Empty:
pass
# check if error occured inside the thread runner
if result is None:
# only raise an error from the runner if all results are consumed
self._report_thread_runner_error(block=True)
# Under normal conditions, this code should never be reached since
# this branch should only be visited if the runner thread raised
# an exception. If no exception were raised, it means that the
# runner thread never reported any results which should not be
# possible when wrapping functions with `wrap_function`.
raise TuneError(
("Wrapped function ran until completion without reporting "
"results or raising an exception."))
else:
if not self._error_queue.empty():
logger.warning(
("Runner error waiting to be raised in main thread. "
"Logging all available results first."))
# This keyword appears if the train_func using the Function API
# finishes without "done=True". This duplicates the last result, but
# the TrialRunner will not log this result again.
if "__duplicate__" in result:
new_result = self._last_result.copy()
new_result.update(result)
result = new_result
self._last_result = result
return result
def _stop(self):
self._status_reporter._stop()
# If everything stayed in synch properly, this should never happen.
if not self._results_queue.empty():
logger.warning(
("Some results were added after the trial stop condition. "
"These results won't be logged."))
# Check for any errors that might have been missed.
self._report_thread_runner_error()
def _report_thread_runner_error(self, block=False):
try:
err_type, err_value, err_tb = self._error_queue.get(
block=block, timeout=ERROR_FETCH_TIMEOUT)
raise TuneError(("Trial raised a {err_type} exception with value: "
"{err_value}\nWith traceback:\n{err_tb}").format(
err_type=err_type,
err_value=err_value,
err_tb=err_tb))
except queue.Empty:
pass
def wrap_function(train_func):
class WrappedFunc(FunctionRunner):
def _trainable_func(self, config, reporter):
output = train_func(config, reporter)
# If train_func returns, we need to notify the main event loop
# of the last result while avoiding double logging. This is done
# with the keyword "__duplicate__" -- see tune/trial_runner.py,
reporter(done=True, __duplicate__=True)
return output
return WrappedFunc