|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from importlib.util import find_spec |
| 4 | + |
| 5 | +import pytest |
| 6 | + |
| 7 | +torch = pytest.importorskip("torch") |
| 8 | +pytest.importorskip("ray") |
| 9 | +pytest.importorskip("fairchem.core") |
| 10 | + |
| 11 | +if find_spec("fairchem"): |
| 12 | + from huggingface_hub.utils._auth import get_token |
| 13 | + |
| 14 | + if not get_token(): |
| 15 | + pytest.skip( |
| 16 | + "HF_TOKEN required for fairchem ray-serve tests", allow_module_level=True |
| 17 | + ) |
| 18 | + |
| 19 | +import numpy as np |
| 20 | +from ase.build import bulk |
| 21 | + |
| 22 | +from quacc import get_settings |
| 23 | +from quacc.recipes.mlp._base import pick_calculator |
| 24 | +from quacc.recipes.mlp.core import relax_job, static_job |
| 25 | +from quacc.recipes.mlp.elastic import elastic_tensor_flow |
| 26 | + |
| 27 | + |
| 28 | +@pytest.fixture(scope="module") |
| 29 | +def ray_serve_cluster(): |
| 30 | + """Spin up a local Ray cluster + multiplexed fairchem serve deployment. |
| 31 | +
|
| 32 | + The deployment is named ``predict-server`` to match what |
| 33 | + ``quacc.recipes.mlp._base`` connects to when |
| 34 | + ``FAIRCHEM_RAY_SERVE_BATCHING`` is enabled. |
| 35 | + """ |
| 36 | + import ray |
| 37 | + from fairchem.core.components.batch_server import ( |
| 38 | + setup_multiplexed_batch_predict_server, |
| 39 | + ) |
| 40 | + from ray import serve |
| 41 | + |
| 42 | + started_ray = False |
| 43 | + if not ray.is_initialized(): |
| 44 | + ray.init( |
| 45 | + include_dashboard=False, |
| 46 | + ignore_reinit_error=True, |
| 47 | + log_to_driver=False, |
| 48 | + configure_logging=False, |
| 49 | + ) |
| 50 | + started_ray = True |
| 51 | + |
| 52 | + handle = setup_multiplexed_batch_predict_server( |
| 53 | + deployment_name="predict-server", |
| 54 | + route_prefix="/predict-server", |
| 55 | + num_replicas=1, |
| 56 | + ray_actor_options={"num_cpus": 1}, |
| 57 | + ) |
| 58 | + try: |
| 59 | + yield handle |
| 60 | + finally: |
| 61 | + try: |
| 62 | + serve.shutdown() |
| 63 | + finally: |
| 64 | + if started_ray and ray.is_initialized(): |
| 65 | + ray.shutdown() |
| 66 | + |
| 67 | + |
| 68 | +@pytest.fixture |
| 69 | +def _batching(monkeypatch, request, ray_serve_cluster): |
| 70 | + settings = get_settings() |
| 71 | + monkeypatch.setattr( |
| 72 | + settings, "FAIRCHEM_RAY_SERVE_BATCHING", request.param, raising=False |
| 73 | + ) |
| 74 | + # pick_calculator is wrapped by freezeargs(lru_cache(...)); clear the |
| 75 | + # underlying lru_cache so each parametrize value rebuilds the calc |
| 76 | + # under the current FAIRCHEM_RAY_SERVE_BATCHING setting. |
| 77 | + pick_calculator.__wrapped__.cache_clear() |
| 78 | + yield request.param |
| 79 | + pick_calculator.__wrapped__.cache_clear() |
| 80 | + |
| 81 | + |
| 82 | +def _assert_calc_path(batching): |
| 83 | + """Verify the calculator built during the test actually used the |
| 84 | + expected code path (Ray Serve batching vs. local inference).""" |
| 85 | + from fairchem.core.units.mlip_unit.predict import BatchServerPredictUnit |
| 86 | + |
| 87 | + calc = pick_calculator( |
| 88 | + method="fairchem", name_or_path="uma-s-1p1", task_name="omat" |
| 89 | + ) |
| 90 | + used_batching = isinstance(getattr(calc, "predictor", None), BatchServerPredictUnit) |
| 91 | + assert used_batching is batching, ( |
| 92 | + f"Expected FAIRCHEM_RAY_SERVE_BATCHING={batching} path, " |
| 93 | + f"but BatchServerPredictUnit usage was {used_batching}." |
| 94 | + ) |
| 95 | + |
| 96 | + |
| 97 | +@pytest.mark.parametrize("_batching", [False, True], indirect=True) |
| 98 | +def test_static_job(tmp_path, monkeypatch, _batching): |
| 99 | + monkeypatch.chdir(tmp_path) |
| 100 | + torch.set_default_dtype(torch.float32) |
| 101 | + |
| 102 | + atoms = bulk("Cu") |
| 103 | + output = static_job( |
| 104 | + atoms, method="fairchem", name_or_path="uma-s-1p1", task_name="omat" |
| 105 | + ) |
| 106 | + assert output["results"]["energy"] == pytest.approx(-3.7501682869643735, rel=1e-3) |
| 107 | + assert np.shape(output["results"]["forces"]) == (1, 3) |
| 108 | + assert output["atoms"] == atoms |
| 109 | + _assert_calc_path(_batching) |
| 110 | + |
| 111 | + |
| 112 | +@pytest.mark.parametrize("_batching", [False, True], indirect=True) |
| 113 | +def test_relax_job(tmp_path, monkeypatch, _batching): |
| 114 | + monkeypatch.chdir(tmp_path) |
| 115 | + torch.set_default_dtype(torch.float32) |
| 116 | + |
| 117 | + atoms = bulk("Cu") * (2, 2, 2) |
| 118 | + atoms[0].position += 0.1 |
| 119 | + output = relax_job( |
| 120 | + atoms, method="fairchem", name_or_path="uma-s-1p1", task_name="omat" |
| 121 | + ) |
| 122 | + assert output["results"]["energy"] == pytest.approx(-30.001143639922756, rel=1e-3) |
| 123 | + assert np.shape(output["results"]["forces"]) == (8, 3) |
| 124 | + assert output["atoms"] != atoms |
| 125 | + assert output["atoms"].get_volume() == pytest.approx(atoms.get_volume()) |
| 126 | + _assert_calc_path(_batching) |
| 127 | + |
| 128 | + |
| 129 | +@pytest.mark.parametrize("_batching", [False, True], indirect=True) |
| 130 | +def test_relax_cell_job(tmp_path, monkeypatch, _batching): |
| 131 | + monkeypatch.chdir(tmp_path) |
| 132 | + torch.set_default_dtype(torch.float32) |
| 133 | + |
| 134 | + atoms = bulk("Cu") * (2, 2, 2) |
| 135 | + atoms[0].position += 0.1 |
| 136 | + output = relax_job( |
| 137 | + atoms, |
| 138 | + method="fairchem", |
| 139 | + relax_cell=True, |
| 140 | + name_or_path="uma-s-1p1", |
| 141 | + task_name="omat", |
| 142 | + ) |
| 143 | + assert output["results"]["energy"] == pytest.approx(-30.005004590392726, rel=1e-3) |
| 144 | + assert np.shape(output["results"]["forces"]) == (8, 3) |
| 145 | + assert output["atoms"] != atoms |
| 146 | + assert output["atoms"].get_volume() != pytest.approx(atoms.get_volume()) |
| 147 | + _assert_calc_path(_batching) |
| 148 | + |
| 149 | + |
| 150 | +@pytest.mark.parametrize("_batching", [False, True], indirect=True) |
| 151 | +def test_elastic_jobs(tmp_path, monkeypatch, _batching): |
| 152 | + monkeypatch.chdir(tmp_path) |
| 153 | + torch.set_default_dtype(torch.float32) |
| 154 | + |
| 155 | + atoms = bulk("Cu") |
| 156 | + outputs = elastic_tensor_flow( |
| 157 | + atoms, |
| 158 | + run_static=False, |
| 159 | + pre_relax=True, |
| 160 | + job_params={ |
| 161 | + "all": { |
| 162 | + "method": "fairchem", |
| 163 | + "name_or_path": "uma-s-1p1", |
| 164 | + "task_name": "omat", |
| 165 | + }, |
| 166 | + "relax_job": {"opt_params": {"fmax": 0.01}}, |
| 167 | + }, |
| 168 | + ) |
| 169 | + assert outputs["deformed_results"][0]["atoms"].get_volume() != pytest.approx( |
| 170 | + atoms.get_volume() |
| 171 | + ) |
| 172 | + assert outputs["undeformed_result"]["results"]["stress"] == pytest.approx( |
| 173 | + 0, abs=1e-2 |
| 174 | + ) |
| 175 | + assert outputs["elasticity_doc"].bulk_modulus.voigt == pytest.approx(151.367, abs=2) |
| 176 | + _assert_calc_path(_batching) |
0 commit comments