From 4cc4bb2ecc968275f47d5e13d12c21ae5aecb024 Mon Sep 17 00:00:00 2001 From: r0c0y <184822225+r0c0y@users.noreply.github.com> Date: Sun, 6 Dec 2026 06:52:00 +0530 Subject: [PATCH] Count the workers as they change when computing the overhead overhead() divided each evaluation's time by the number of workers when it finished and the sum by the elapsed time, which only holds while that number stays the same. With a scaling cluster the evaluations that finish after a scale-down counted several times over and the overhead went negative (#187); after a scale-up it was too high. Divide the total function time by the worker-seconds offered instead, summed piece by piece as the number of workers or of pending points changes, with max(n_workers, n_pending) as the capacity, so the overhead stays between 0 and 100. With a fixed number of workers the result is the same, and the number of workers is now read once per iteration, not per finished point. Fixes #187 --- adaptive/runner.py | 56 +++++++++++++++++------ adaptive/tests/test_runner.py | 84 +++++++++++++++++++++++++++++++++++ 2 files changed, 127 insertions(+), 13 deletions(-) diff --git a/adaptive/runner.py b/adaptive/runner.py index 99f1f4e4..5096b035 100644 --- a/adaptive/runner.py +++ b/adaptive/runner.py @@ -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. """ @@ -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 @@ -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 ----- @@ -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, @@ -259,13 +284,15 @@ 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, @@ -273,7 +300,11 @@ def _get_futures( # 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] @@ -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): @@ -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. """ @@ -569,7 +598,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 ----- diff --git a/adaptive/tests/test_runner.py b/adaptive/tests/test_runner.py index 0bb68c59..5947dcc4 100644 --- a/adaptive/tests/test_runner.py +++ b/adaptive/tests/test_runner.py @@ -1,10 +1,13 @@ import platform import sys import time +from concurrent.futures import Executor, Future, ThreadPoolExecutor +from types import SimpleNamespace import numpy as np import pytest +import adaptive.runner from adaptive.learner import ( BalancingLearner, DataSaver, @@ -263,3 +266,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)