diff --git a/autofit/non_linear/jax_compile.py b/autofit/non_linear/jax_compile.py index 69db63df3..f57fe1c2f 100644 --- a/autofit/non_linear/jax_compile.py +++ b/autofit/non_linear/jax_compile.py @@ -1,8 +1,176 @@ +import faulthandler import logging +import os +import threading import time logger = logging.getLogger(__name__) +# How often a compile that is still running reports that it is still alive. +DEFAULT_HEARTBEAT_SECONDS = 30.0 + +# How long a first compile may run under CI before it dumps its own traceback. +# Off by default off-CI: an interactive user watching a slow compile does not +# want a traceback on stderr, they want the heartbeat above. +DEFAULT_CI_DUMP_SECONDS = 300.0 + + +def _env_seconds(name, default): + """ + Read a non-negative number of seconds from the environment. + + A malformed value warns and falls back rather than raising: every consumer + of this module is diagnostics wrapped around a model-fit, and diagnostics + must never be the reason a fit dies. + """ + value = os.environ.get(name) + + if value is None: + return default + + try: + seconds = float(value) + except ValueError: + logger.warning( + f"Ignoring {name}={value!r}: expected a number of seconds. " + f"Using {default} instead." + ) + return default + + return max(seconds, 0.0) + + +def heartbeat_seconds(): + """ + The interval between "still compiling" log lines, from + `PYAUTOFIT_JAX_COMPILE_HEARTBEAT_SECS`. `0` disables the heartbeat. + """ + return _env_seconds( + "PYAUTOFIT_JAX_COMPILE_HEARTBEAT_SECS", DEFAULT_HEARTBEAT_SECONDS + ) + + +def dump_traceback_seconds(): + """ + How long a first compile may run before dumping a traceback, from + `PYAUTOFIT_JAX_COMPILE_DUMP_SECS`. `0` disables the dump. + + The default is on under CI and off elsewhere. That is what makes a stalled + CI run self-diagnosing without editing a single workspace script or CI + runner -- the alternative, threading an environment variable through each + workspace's `config/build/env_vars_*.yaml`, is more repos touched for the + same effect, and the workspace scripts are user-facing documentation. + """ + default = DEFAULT_CI_DUMP_SECONDS if os.environ.get("CI") else 0.0 + return _env_seconds("PYAUTOFIT_JAX_COMPILE_DUMP_SECS", default) + + +class _Heartbeat: + """ + Log that a compile is still running, on an interval, until stopped. + + Without this a long compile is indistinguishable from a stopped one: the + process emits the "compiling..." line and then nothing at all until it + either finishes or is killed. Several CI stalls were quarantined without + diagnosis for exactly that reason -- there was no evidence to diagnose from. + + The thread is a daemon and waits on an `Event`, so it neither holds the + interpreter open at exit nor sleeps past `stop`. + """ + + def __init__(self, description, start, interval=None): + self.description = description + self.start_time = start + self.interval = heartbeat_seconds() if interval is None else interval + self._stop = threading.Event() + self._thread = None + + def _beat(self): + while not self._stop.wait(self.interval): + logger.info( + f"JAX jit still compiling {self.description}, " + f"{time.time() - self.start_time:.0f}s elapsed..." + ) + + def start(self): + if self.interval <= 0: + return + + thread = threading.Thread( + target=self._beat, + name="jax-compile-heartbeat", + daemon=True, + ) + + try: + thread.start() + except RuntimeError as e: + # Out of threads. Losing the heartbeat is a lost diagnostic; letting + # it raise here would make this instrumentation the reason a fit + # died, which is the opposite of the point. + logger.debug(f"Could not start the JAX compile heartbeat: {e}") + return + + self._thread = thread + + def stop(self): + self._stop.set() + + if self._thread is not None: + self._thread.join(timeout=self.interval) + self._thread = None + + +class _TracebackWatchdog: + """ + Arm `faulthandler` so a compile that overruns dumps its own traceback. + + A stalled run used to be killed by the runner's cap having emitted nothing + since the "compiling..." line, so there was no way to tell whether it was + inside XLA, inside execution, or blocked on a lock. This makes the process + say so itself, before anything kills it. + + Note the limitation: a Python traceback taken during XLA compilation parks + at the pybind boundary and will not show XLA internals. It still separates + *in compile* from *in execution* from *blocked on a Python-level lock* -- + for instance the persistent compilation cache -- which is the distinction + that matters here. + + `faulthandler`'s timer is process-global, so nested or concurrent first + compiles share one. That is benign for the callers here, which compile on + the main thread one at a time. + """ + + def __init__(self, seconds=None): + self.seconds = dump_traceback_seconds() if seconds is None else seconds + self._armed = False + + def arm(self): + if self.seconds <= 0: + return + + try: + faulthandler.dump_traceback_later( + self.seconds, repeat=True, exit=False + ) + except Exception as e: + # `dump_traceback_later` needs a stderr with a real file descriptor, + # which a capturing harness may not provide. Losing the dump is a + # lost diagnostic, never a failed fit. + logger.debug(f"Could not arm the JAX compile traceback dump: {e}") + return + + self._armed = True + + def cancel(self): + # Only cancel a timer this object armed -- cancelling unconditionally + # would silently disarm a `faulthandler` timer set by the caller. + if not self._armed: + return + + faulthandler.cancel_dump_traceback_later() + self._armed = False + def log_on_first_compile(func, description): """ @@ -17,6 +185,19 @@ def log_on_first_compile(func, description): yet and reported a duration of roughly zero, leaving the real wait that followed unexplained. + That first call contains two different waits, and this reports them + separately: + + 1. `func(*args, **kwargs)` -- tracing, lowering and XLA compilation; + 2. `jax.block_until_ready(result)` -- execution, since JAX dispatches + asynchronously. + + One summary line covering both cannot say which half a stalled run is stuck + in, and that ambiguity is why the same intermittent stall has been + quarantined three times across the test workspaces without a diagnosis. A + heartbeat reports liveness while either half is in flight, and a + `faulthandler` watchdog dumps a traceback if the whole thing overruns. + The one-shot flag lives in a closure rather than on an object because the callers cache these wrappers on attributes that are stripped for pickling; a fresh process rebuilds the wrapper and genuinely does recompile, so it @@ -44,8 +225,15 @@ def wrapper(*args, **kwargs): ) start = time.time() + heartbeat = _Heartbeat(description, start) + watchdog = _TracebackWatchdog() + + heartbeat.start() + watchdog.arm() + try: result = func(*args, **kwargs) + compiled_at = time.time() # JAX dispatches asynchronously, so `result` may be a future that is # not yet materialized. Block once, on this first call only, so the @@ -57,9 +245,19 @@ def wrapper(*args, **kwargs): jax.block_until_ready(result) except Exception: pass + + materialized_at = time.time() finally: + watchdog.cancel() + heartbeat.stop() state["compiled"] = True + logger.info( + f"JAX jit compilation of {description}: traced, lowered and " + f"compiled in {compiled_at - start:.1f} seconds, result " + f"materialized in {materialized_at - compiled_at:.1f} seconds." + ) + logger.info( f"JAX jit compilation of {description} complete in " f"{time.time() - start:.1f} seconds." diff --git a/test_autofit/non_linear/test_jax_compile.py b/test_autofit/non_linear/test_jax_compile.py index 22862f2c8..e3981f300 100644 --- a/test_autofit/non_linear/test_jax_compile.py +++ b/test_autofit/non_linear/test_jax_compile.py @@ -1,5 +1,9 @@ import logging +import threading +import time +from unittest import mock +from autofit.non_linear import jax_compile from autofit.non_linear.jax_compile import log_on_first_compile # ``log_on_first_compile`` wraps the jax.jit / jax.vmap / jax.grad callables so the @@ -80,3 +84,198 @@ def boom(_): # "completed in N seconds" after it raised would not be. assert any("could take seconds or minutes" in m for m in messages) assert not any("complete in" in m for m in messages) + + +# The stall this instrumentation exists for: a first compile that emits the +# "compiling..." line and then nothing at all until a CI cap kills it. The tests +# below pin the three things that turn that silence into evidence -- a +# heartbeat, a faulthandler dump, and a compile-vs-execute timing split -- and, +# as above, none of them needs JAX installed. + + +def test_a_slow_first_call_reports_that_it_is_still_alive(caplog): + wrapped = log_on_first_compile(lambda: time.sleep(0.25), "likelihood function") + + with caplog.at_level(logging.INFO, logger=LOGGER): + with mock.patch.object(jax_compile, "heartbeat_seconds", return_value=0.05): + wrapped() + + beats = [ + record + for record in caplog.records + if "still compiling likelihood function" in record.getMessage() + ] + + # Without these the log cannot distinguish a compile that is slow from one + # that has stopped, which is the whole diagnostic gap. + assert beats + + +def test_the_heartbeat_stops_when_the_compile_does(caplog): + wrapped = log_on_first_compile(lambda: None, "likelihood function") + + with caplog.at_level(logging.INFO, logger=LOGGER): + with mock.patch.object(jax_compile, "heartbeat_seconds", return_value=0.05): + wrapped() + + before = len(caplog.records) + time.sleep(0.2) + + # A heartbeat thread that outlived its compile would log against every + # later evaluation, and there are millions of those per fit. + assert len(caplog.records) == before + + assert not any( + thread.name == "jax-compile-heartbeat" for thread in threading.enumerate() + ) + + +def test_the_heartbeat_can_be_disabled(caplog): + wrapped = log_on_first_compile(lambda: time.sleep(0.15), "likelihood function") + + with caplog.at_level(logging.INFO, logger=LOGGER): + with mock.patch.object(jax_compile, "heartbeat_seconds", return_value=0.0): + wrapped() + + assert not any( + "still compiling" in record.getMessage() for record in caplog.records + ) + + +def test_the_traceback_dump_is_armed_for_the_compile_and_cancelled_after(): + wrapped = log_on_first_compile(lambda: None, "likelihood function") + + with mock.patch.object(jax_compile, "dump_traceback_seconds", return_value=120.0): + with mock.patch.object(jax_compile.faulthandler, "dump_traceback_later") as arm: + with mock.patch.object( + jax_compile.faulthandler, "cancel_dump_traceback_later" + ) as cancel: + wrapped() + + arm.assert_called_once_with(120.0, repeat=True, exit=False) + cancel.assert_called_once() + + +def test_the_traceback_dump_is_cancelled_even_when_the_compile_raises(): + def boom(): + raise ValueError("compile failed") + + wrapped = log_on_first_compile(boom, "likelihood function") + + with mock.patch.object(jax_compile, "dump_traceback_seconds", return_value=120.0): + with mock.patch.object(jax_compile.faulthandler, "dump_traceback_later"): + with mock.patch.object( + jax_compile.faulthandler, "cancel_dump_traceback_later" + ) as cancel: + try: + wrapped() + except ValueError: + pass + + # A timer left armed would fire against whatever ran next and report an + # unrelated stack as the stalled one. + cancel.assert_called_once() + + +def test_a_disabled_traceback_dump_arms_nothing_and_cancels_nothing(): + wrapped = log_on_first_compile(lambda: None, "likelihood function") + + with mock.patch.object(jax_compile, "dump_traceback_seconds", return_value=0.0): + with mock.patch.object(jax_compile.faulthandler, "dump_traceback_later") as arm: + with mock.patch.object( + jax_compile.faulthandler, "cancel_dump_traceback_later" + ) as cancel: + wrapped() + + arm.assert_not_called() + # Cancelling unconditionally would disarm a faulthandler timer the caller + # set for their own reasons. + cancel.assert_not_called() + + +def test_a_dump_that_cannot_be_armed_does_not_break_the_compile(caplog): + wrapped = log_on_first_compile(lambda: "fit", "likelihood function") + + with mock.patch.object(jax_compile, "dump_traceback_seconds", return_value=120.0): + with mock.patch.object( + jax_compile.faulthandler, + "dump_traceback_later", + side_effect=RuntimeError("sys.stderr has no file descriptor"), + ): + with caplog.at_level(logging.INFO, logger=LOGGER): + assert wrapped() == "fit" + + # A capturing harness can leave stderr without a real fd. Losing the dump is + # a lost diagnostic, never a failed fit. + assert any("complete in" in record.getMessage() for record in caplog.records) + + +def test_the_compile_wait_and_the_execution_wait_are_reported_separately(caplog): + wrapped = log_on_first_compile(lambda: None, "vectorized (vmap) likelihood function") + + with caplog.at_level(logging.INFO, logger=LOGGER): + wrapped() + + messages = [record.getMessage() for record in caplog.records] + + # One summary line covering both waits cannot say which half a stalled run + # is stuck in -- the ambiguity this whole module exists to remove. + assert any( + "traced, lowered and compiled in" in m and "result materialized in" in m + for m in messages + ) + + +def test_the_split_is_not_reported_when_the_first_call_raises(caplog): + def boom(): + raise ValueError("compile failed") + + wrapped = log_on_first_compile(boom, "likelihood function") + + with caplog.at_level(logging.INFO, logger=LOGGER): + try: + wrapped() + except ValueError: + pass + + messages = [record.getMessage() for record in caplog.records] + + assert not any("traced, lowered and compiled in" in m for m in messages) + + +def test_the_heartbeat_interval_comes_from_the_environment(monkeypatch): + monkeypatch.delenv("PYAUTOFIT_JAX_COMPILE_HEARTBEAT_SECS", raising=False) + assert jax_compile.heartbeat_seconds() == jax_compile.DEFAULT_HEARTBEAT_SECONDS + + monkeypatch.setenv("PYAUTOFIT_JAX_COMPILE_HEARTBEAT_SECS", "5") + assert jax_compile.heartbeat_seconds() == 5.0 + + monkeypatch.setenv("PYAUTOFIT_JAX_COMPILE_HEARTBEAT_SECS", "0") + assert jax_compile.heartbeat_seconds() == 0.0 + + +def test_the_traceback_dump_defaults_on_under_ci_and_off_elsewhere(monkeypatch): + monkeypatch.delenv("PYAUTOFIT_JAX_COMPILE_DUMP_SECS", raising=False) + + monkeypatch.delenv("CI", raising=False) + assert jax_compile.dump_traceback_seconds() == 0.0 + + # The point of the default: the next CI stall dumps a stack with no + # workspace script and no CI runner edited. + monkeypatch.setenv("CI", "true") + assert jax_compile.dump_traceback_seconds() == jax_compile.DEFAULT_CI_DUMP_SECONDS + + monkeypatch.setenv("PYAUTOFIT_JAX_COMPILE_DUMP_SECS", "60") + assert jax_compile.dump_traceback_seconds() == 60.0 + + monkeypatch.setenv("PYAUTOFIT_JAX_COMPILE_DUMP_SECS", "0") + assert jax_compile.dump_traceback_seconds() == 0.0 + + +def test_a_malformed_interval_falls_back_rather_than_raising(monkeypatch): + monkeypatch.setenv("PYAUTOFIT_JAX_COMPILE_HEARTBEAT_SECS", "soon") + assert jax_compile.heartbeat_seconds() == jax_compile.DEFAULT_HEARTBEAT_SECONDS + + # A negative interval would busy-loop the heartbeat thread. + monkeypatch.setenv("PYAUTOFIT_JAX_COMPILE_HEARTBEAT_SECS", "-5") + assert jax_compile.heartbeat_seconds() == 0.0