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
51 changes: 43 additions & 8 deletions autofit/non_linear/parallel/pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,8 @@ class ParallelResolution:
The analysis's resolved compute setup (``analysis.setup.setup_id``), or ``None``.
cpus_per_eval, peak_rss_gb
The analysis's ``resources_per_eval()`` (``None`` when it declares none).
is_jax
Whether the analysis is JAX (the banner then reports the JAX device).
"""

requested: Union[int, str]
Expand All @@ -189,6 +191,7 @@ class ParallelResolution:
setup_id: Optional[str] = None
cpus_per_eval: Optional[float] = None
peak_rss_gb: Optional[float] = None
is_jax: bool = False

@property
def reason_text(self) -> str:
Expand Down Expand Up @@ -218,16 +221,27 @@ def reason_text(self) -> str:
def banner(self) -> str:
"""
The one INFO line a fit logs once its compute setup is resolved, e.g.
``Parallel: 64 workers (requested auto; detected cores) · setup numba_cpu_sparse_fp64``.
``Parallel: 64 workers (auto: detected cores)``, ``Parallel: 4 workers (requested 4)``
or ``Parallel: 1 worker (JAX on GPU: NVIDIA A100-SXM4-80GB)``.

The compute setup is not repeated here (the fit's ``Setup:`` line reports it);
``search.summary`` and ``files/parallel.json`` still record ``setup_id``.
"""
workers = "worker" if self.number_of_cores == 1 else "workers"
detail = f"requested {self.requested}"
if self.reason_text:
detail += f"; {self.reason_text}"
line = f"Parallel: {self.number_of_cores} {workers} ({detail})"
if self.setup_id is not None:
line += f" · setup {self.setup_id}"
return line
auto = is_auto(self.requested)

if self.is_jax or self.reason == "jax":
detail = jax_device_text()
if not auto and self.requested != 1:
detail = f"requested {self.requested}; {detail}"
elif self.reason == "expectation_propagation":
detail = "expectation-propagation factor search"
elif self.reason == "requested" or not auto:
detail = f"requested {self.requested}"
else:
detail = f"auto: {self.reason_text}"

return f"Parallel: {self.number_of_cores} {workers} ({detail})"

@property
def summary(self) -> str:
Expand Down Expand Up @@ -266,6 +280,26 @@ def to_dict(self) -> dict:
}


def jax_device_text() -> str:
"""
``"JAX on CPU"`` or ``"JAX on GPU: <device name>"`` for the first JAX device, read
only when JAX is already imported (this never imports JAX just to report it);
``"JAX"`` when it is not imported or the device cannot be read.
"""
jax = sys.modules.get("jax")
if jax is None:
return "JAX"
try:
device = jax.devices()[0]
platform = str(device.platform).upper()
if platform == "CPU":
return "JAX on CPU"
name = getattr(device, "device_kind", None)
return f"JAX on {platform}: {name}" if name else f"JAX on {platform}"
except Exception:
return "JAX"


def _number(value) -> str:
"""
``value`` without a trailing ``.0`` when it is whole.
Expand Down Expand Up @@ -391,6 +425,7 @@ def resolution(n, reason, **kwargs):
number_of_cores=n,
reason=reason,
setup_id=setup_id,
is_jax=bool(is_jax),
**kwargs,
)

Expand Down
26 changes: 7 additions & 19 deletions autofit/non_linear/search/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,27 +244,15 @@ def decorated(self, *args, **kwargs):

def log_fit_start(search, analysis):
"""
Log, once at the start of a fit, the JAX device a JAX analysis runs on and the
quick-update cadence (``NonLinearSearch.quick_update_message``).
Log, once at the start of a fit, that the search is starting and its quick-update
cadence (``NonLinearSearch.quick_update_message``).

The worker count is not logged here: it is only known once ``modify_before_fit``
has resolved the analysis's compute setup, and the fit's one ``Parallel:`` banner
line reports it (``resolve_fit_parallel``).
Neither the backend nor the worker count is claimed here: both are only known once
``modify_before_fit`` has resolved the analysis's compute setup, and the fit's
``Setup:`` and ``Parallel:`` lines report them (the JAX device is in ``Parallel:``,
``resolve_fit_parallel``).
"""
if analysis.is_jax:
try:
import jax

device = jax.devices()[0]
backend = device.platform.upper()
device_name = getattr(device, "device_kind", backend)
logger.info(
f"Starting non-linear search with JAX ({backend}: {device_name})."
)
except Exception:
logger.info("Starting non-linear search with JAX.")
else:
logger.info("Starting non-linear search.")
logger.info("Starting non-linear search.")
logger.info(search.quick_update_message)


Expand Down
2 changes: 1 addition & 1 deletion test_autofit/graphical/test_factor_graph_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,5 +179,5 @@ def modify_before_fit(self, paths, model):

banners = [r.getMessage() for r in caplog.records if r.getMessage().startswith("Parallel:")]
assert banners == [
"Parallel: 8 workers (requested auto; detected cores) · setup numba_cpu_sparse_fp64"
"Parallel: 8 workers (auto: detected cores)"
]
84 changes: 70 additions & 14 deletions test_autofit/non_linear/test_number_of_cores_auto.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,27 +131,74 @@ def test_auto_resolves_to_detected_cores():
assert resolution.reason == "detected_cores"
assert resolution.detected_cores == 64
assert resolution.available_memory_gb is None
assert resolution.banner == (
"Parallel: 64 workers (requested auto; detected cores) · setup numba_cpu_sparse_fp64"
)
assert resolution.banner == "Parallel: 64 workers (auto: detected cores)"
# The setup is reported by the fit's `Setup:` line, not repeated in `Parallel:`, but
# `search.summary` and `parallel.json` keep it.
assert resolution.setup_id == "numba_cpu_sparse_fp64"
assert "Setup = numba_cpu_sparse_fp64" in resolution.summary
assert resolution.to_dict()["setup_id"] == "numba_cpu_sparse_fp64"


class _FakeDevice:
def __init__(self, platform, device_kind):
self.platform = platform
self.device_kind = device_kind


class _FakeJax:
def __init__(self, device):
self._device = device

def devices(self):
return [self._device]

def test_auto_under_jax_is_one():

def test_auto_under_jax_is_one_and_says_jax_when_jax_is_not_imported(monkeypatch):
import sys

monkeypatch.delitem(sys.modules, "jax", raising=False)
resolution = resolve_number_of_cores("auto", _Analysis(is_jax=True))
assert resolution.number_of_cores == 1
assert resolution.banner == (
"Parallel: 1 worker (requested auto; JAX analyses run single-process)"
assert resolution.banner == "Parallel: 1 worker (JAX)"
assert "jax" not in sys.modules


def test_jax_banner_reports_the_cpu_device(monkeypatch):
import sys

monkeypatch.setitem(sys.modules, "jax", _FakeJax(_FakeDevice("cpu", "cpu")))
resolution = resolve_number_of_cores("auto", _Analysis(is_jax=True))
assert resolution.banner == "Parallel: 1 worker (JAX on CPU)"


def test_jax_banner_reports_the_gpu_device(monkeypatch):
import sys

monkeypatch.setitem(
sys.modules, "jax", _FakeJax(_FakeDevice("gpu", "NVIDIA A100-SXM4-80GB"))
)
resolution = resolve_number_of_cores("auto", _Analysis(is_jax=True))
assert resolution.banner == "Parallel: 1 worker (JAX on GPU: NVIDIA A100-SXM4-80GB)"

one = resolve_number_of_cores(1, _Analysis(is_jax=True))
assert one.banner == "Parallel: 1 worker (JAX on GPU: NVIDIA A100-SXM4-80GB)"


def test_int_request_under_jax_is_one():
def test_int_request_under_jax_is_one(monkeypatch):
import sys

monkeypatch.setitem(sys.modules, "jax", _FakeJax(_FakeDevice("cpu", "cpu")))
resolution = resolve_number_of_cores(4, _Analysis(is_jax=True))
assert (resolution.number_of_cores, resolution.reason) == (1, "jax")
assert resolution.banner == "Parallel: 1 worker (requested 4; JAX on CPU)"


def test_auto_ep_factor_search_is_one():
resolution = resolve_number_of_cores("auto", _Analysis(), ep_factor_search=True)
assert (resolution.number_of_cores, resolution.reason) == (1, "expectation_propagation")
assert resolution.banner == (
"Parallel: 1 worker (expectation-propagation factor search)"
)


def test_ep_check_accepts_auto_and_refuses_an_explicit_count():
Expand All @@ -173,7 +220,7 @@ def test_memory_cap(monkeypatch):
assert resolution.reason == "memory"
assert resolution.available_memory_gb == 120.0
assert resolution.banner == (
"Parallel: 48 workers (requested auto; capped by memory: 120.0 GB available "
"Parallel: 48 workers (auto: capped by memory: 120.0 GB available "
"/ 2.5 GB per evaluation)"
)

Expand All @@ -182,6 +229,9 @@ def test_cores_per_eval_cap():
analysis = _Analysis(resources_per_eval={"cpus_per_eval": 4, "peak_rss_gb": 0.5})
resolution = resolve_number_of_cores("auto", analysis)
assert (resolution.number_of_cores, resolution.reason) == (16, "cores_per_eval")
assert resolution.banner == (
"Parallel: 16 workers (auto: capped by cores: 64 cores / 4 CPUs per evaluation)"
)


def test_memory_cap_never_below_one(monkeypatch):
Expand Down Expand Up @@ -337,10 +387,11 @@ def test_fit_logs_one_banner_after_modify_before_fit_and_writes_parallel_json(

banners = _banner_records(caplog)
assert [r.getMessage() for r in banners] == [
"Parallel: 64 workers (requested auto; detected cores) · setup numba_cpu_sparse_fp64"
"Parallel: 64 workers (auto: detected cores)"
]
assert not [r for r in caplog.records if "cores." in r.getMessage()
and r.getMessage().startswith("Starting non-linear search")]
starts = [r.getMessage() for r in caplog.records
if r.getMessage().startswith("Starting non-linear search")]
assert starts == ["Starting non-linear search."]

assert search.number_of_cores == "auto"

Expand Down Expand Up @@ -379,9 +430,14 @@ def test_fit_banner_for_jax_auto(monkeypatch, caplog, tmp_path):
with caplog.at_level(logging.INFO):
search.fit(model=af.Model(af.ex.Gaussian), analysis=analysis)

assert [r.getMessage() for r in _banner_records(caplog)] == [
"Parallel: 1 worker (requested auto; JAX analyses run single-process)"
]
banners = [r.getMessage() for r in _banner_records(caplog)]
assert len(banners) == 1
# "JAX on CPU" here; "JAX on GPU: <name>" on a GPU machine.
assert banners[0].startswith("Parallel: 1 worker (JAX on ")
# The start line makes no backend claim: the device is reported in `Parallel:`.
starts = [r.getMessage() for r in caplog.records
if r.getMessage().startswith("Starting non-linear search")]
assert starts == ["Starting non-linear search."]


# ------------------------------------------------- runtime_estimate hook (5E-2)
Expand Down
Loading