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
56 changes: 43 additions & 13 deletions adaptive/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,8 @@ class BaseRunner(metaclass=abc.ABCMeta):
-------
overhead : callable
The overhead in percent of using Adaptive. Essentially, this is
``100 * (1 - total_elapsed_function_time / self.elapsed_time())``.
``100 * (1 - total_function_time / (n_workers * elapsed_time))``,
with ``n_workers`` counted as it changes.

"""

Expand Down Expand Up @@ -172,7 +173,14 @@ def __init__(
# Timing
self.start_time = time.time()
self.end_time: float | None = None
self._elapsed_function_time = 0
self._elapsed_function_time = 0 # summed over all evaluations
# Worker-seconds the executor offered, which `overhead` divides by.
# The number of workers can change during a run (an adaptively scaling
# cluster), so it is summed piece by piece; see `_count_worker_time`.
self._worker_time = 0.0
self._worker_time_until = self.start_time
self._nworkers = 0
self._capacity: int | None = None

# Error handling attributes
self.retries = retries
Expand Down Expand Up @@ -221,7 +229,10 @@ def _ask(self, n: int) -> tuple[list[int], list[float]]:
def overhead(self) -> float:
"""Overhead of using Adaptive and the executor in percent.

This is measured as ``100 * (1 - t_function / t_elapsed)``.
This is measured as ``100 * (1 - t_function / t_workers)``, where
``t_function`` is the time of all function evaluations together and
``t_workers`` the elapsed time times the number of workers, summed
piece by piece when that number changes.

Notes
-----
Expand All @@ -238,8 +249,22 @@ def overhead(self) -> float:
# When no function is done executing, the overhead cannot
# reliably be determined, so 0 is the best we can do.
return 0
t_total = self.elapsed_time()
return (1 - t_function / t_total) * 100
return (1 - t_function / self._count_worker_time()) * 100

def _count_worker_time(self) -> float:
"""Add the worker-seconds since the last call and return the total.

Between calls the capacity is ``max(n_workers, n_pending)``: when
workers leave while points are still pending, the pending points
count, because the function time is measured from submitting a point
to processing its result. The function time therefore never exceeds
the worker time, so the overhead stays between 0 and 100.
"""
now = time.time() if self.end_time is None else self.end_time
if self._capacity is not None:
self._worker_time += self._capacity * (now - self._worker_time_until)
self._worker_time_until = now
return self._worker_time

def _process_futures(
self,
Expand All @@ -259,21 +284,27 @@ def _process_futures(
if self.raise_if_retries_exceeded:
self._do_raise(e, pid)
else:
self._elapsed_function_time += t / self._get_max_tasks()
self._elapsed_function_time += t
self._to_retry.pop(pid, None)
self._tracebacks.pop(pid, None)
x = self._id_to_point.pop(pid)
if self.do_log:
self.log.append(("tell", x, y)) # type: ignore[union-attr]
self.learner.tell(x, y)
self._count_worker_time()
self._capacity = max(self._nworkers, len(self._pending_tasks))

def _get_futures(
self,
) -> list[FutureTypes]:
# Launch tasks to replace the ones that completed
# on the last iteration, making sure to fill workers
# that have started since the last iteration.
n_new_tasks = max(0, self._get_max_tasks() - len(self._pending_tasks))
self._nworkers = self._get_max_tasks()
self._count_worker_time()
# The new tasks fill up to the number of workers, so this covers them.
self._capacity = max(self._nworkers, len(self._pending_tasks))
n_new_tasks = max(0, self._nworkers - len(self._pending_tasks))

if self.do_log:
self.log.append(("ask", n_new_tasks)) # type: ignore[union-attr]
Expand Down Expand Up @@ -319,10 +350,7 @@ def failed(self) -> set[int]:
@abc.abstractmethod
def elapsed_time(self):
"""Return the total time elapsed since the runner
was started.

Is called in `overhead`.
"""
was started."""

@abc.abstractmethod
def _submit(self, x):
Expand Down Expand Up @@ -415,7 +443,8 @@ class BlockingRunner(BaseRunner):
overhead : callable
The overhead in percent of using Adaptive. This includes the
overhead of the executor. Essentially, this is
``100 * (1 - total_elapsed_function_time / self.elapsed_time())``.
``100 * (1 - total_function_time / (n_workers * elapsed_time))``,
with ``n_workers`` counted as it changes.

"""

Expand Down Expand Up @@ -574,7 +603,8 @@ class AsyncRunner(BaseRunner):
overhead : callable
The overhead in percent of using Adaptive. This includes the
overhead of the executor. Essentially, this is
``100 * (1 - total_elapsed_function_time / self.elapsed_time())``.
``100 * (1 - total_function_time / (n_workers * elapsed_time))``,
with ``n_workers`` counted as it changes.

Notes
-----
Expand Down
85 changes: 84 additions & 1 deletion adaptive/tests/test_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import Executor, Future, ThreadPoolExecutor
from contextlib import contextmanager
from types import SimpleNamespace

import numpy as np
import pytest

import adaptive.runner
from adaptive.learner import (
BalancingLearner,
DataSaver,
Expand Down Expand Up @@ -374,3 +376,84 @@ def counting_ask(self, n, tell_pending=True):
finally:
# Restore original method
Learner1D.ask = original_ask


@pytest.mark.parametrize(
"schedule",
[[(0, 4)], [(0, 4), (0.3, 1)], [(0, 1), (0.3, 4)]],
ids=["constant", "scale-down", "scale-up"],
)
def test_overhead_with_a_changing_number_of_workers(monkeypatch, schedule):
# The executor's workers change during the run, as with an adaptively
# scaling cluster (#187). Dividing each evaluation by the number of workers
# when it finished made the overhead negative after a scale-down.
start = time.time()

def ncores(executor):
elapsed = time.time() - start
return [n for since, n in schedule if elapsed >= since][-1]

monkeypatch.setattr(adaptive.runner, "_get_ncores", ncores)

def f(x):
time.sleep(0.05)
return x

with ThreadPoolExecutor(4) as executor:
runner = BlockingRunner(
Learner1D(f, (-1, 1)), duration_goal=0.6, executor=executor
)
assert 0 <= runner.overhead() < 50


class _ManualExecutor(Executor):
"""Hands out futures that the test completes itself."""

def submit(self, fn, /, *args, **kwargs):
return Future()


@pytest.mark.parametrize(
("steps", "expected"),
[
# Two workers throughout, idle for 0.5 s between the two rounds:
# 5 worker-seconds offered, 4 used. Same as before the change.
([(0, "fill", 2), (1, "finish", 2), (1.5, "fill", 2), (2.5, "finish", 2)], 20),
# Four workers, down to one while the four points are still pending,
# which then finish in two batches; the pending points count as long
# as there are more of them than workers. 10 offered, 9 used.
(
[(0, "fill", 4), (1, "fill", 1), (2, "finish", 2), (2.5, "finish", 2)]
+ [(3.5, "idle", 0)],
10,
),
# One worker, up to three after an idle second: 5 offered, 4 used.
([(0, "fill", 1), (1, "finish", 1), (2, "fill", 3), (3, "finish", 3)], 20),
],
ids=["constant", "scale-down", "scale-up"],
)
def test_overhead_is_the_share_of_unused_worker_time(monkeypatch, steps, expected):
clock = SimpleNamespace(now=0.0)
workers = SimpleNamespace(n=1)
monkeypatch.setattr(
adaptive.runner, "time", SimpleNamespace(time=lambda: clock.now)
)
monkeypatch.setattr(adaptive.runner, "_get_ncores", lambda executor: workers.n)

# A goal that is met at once, so that the test drives the runner itself.
runner = BlockingRunner(
Learner1D(lambda x: x, (-1, 1)), goal=lambda _: True, executor=_ManualExecutor()
)
runner.end_time = None
pending = []
for now, action, n in steps:
clock.now = now
if action == "fill": # the executor has n workers, the runner fills them
workers.n = n
pending += [fut for fut in runner._get_futures() if fut not in pending]
elif action == "finish": # the n oldest points finish
done, pending = pending[:n], pending[n:]
for fut in done:
fut.set_result(0.0)
runner._process_futures(set(done))
assert runner.overhead() == pytest.approx(expected)
Loading