|
| 1 | +# SPDX-License-Identifier: LGPL-3.0-or-later |
| 2 | +"""Test the TF2 ZBL model factory deep-copies input and injects type_map. |
| 3 | +
|
| 4 | +The TF2 (and JAX) ZBL factory used to mutate the caller's config in place and |
| 5 | +did not propagate ``type_map`` into the descriptor and fitting sub-configs, |
| 6 | +unlike the standard and dpmodel factories. This checks the factory leaves the |
| 7 | +input dict unchanged and that the constructed descriptor and fitting carry the |
| 8 | +model ``type_map``. Gated on the TF2 backend (``DEEPMD_TEST_TF2=1``). |
| 9 | +""" |
| 10 | + |
| 11 | +import os |
| 12 | +import unittest |
| 13 | +from copy import ( |
| 14 | + deepcopy, |
| 15 | +) |
| 16 | + |
| 17 | +from .common import ( |
| 18 | + INSTALLED_TF2, |
| 19 | +) |
| 20 | + |
| 21 | +if INSTALLED_TF2: |
| 22 | + from deepmd.tf2.model.model import ( |
| 23 | + get_zbl_model, |
| 24 | + ) |
| 25 | + |
| 26 | +TESTS_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 27 | +SRTAB = os.path.join( |
| 28 | + TESTS_DIR, "pt", "water", "data", "zbl_tab_potential", "H2O_tab_potential.txt" |
| 29 | +) |
| 30 | + |
| 31 | + |
| 32 | +def _zbl_config() -> dict: |
| 33 | + return { |
| 34 | + "type_map": ["O", "H", "B"], |
| 35 | + "use_srtab": SRTAB, |
| 36 | + "sw_rmin": 0.2, |
| 37 | + "sw_rmax": 4.0, |
| 38 | + "smin_alpha": 0.1, |
| 39 | + # ZBL wraps a linear atomic model, which requires a mixed-type descriptor |
| 40 | + "descriptor": { |
| 41 | + "type": "se_atten", |
| 42 | + "sel": 40, |
| 43 | + "rcut_smth": 0.5, |
| 44 | + "rcut": 4.0, |
| 45 | + "neuron": [3, 6], |
| 46 | + "axis_neuron": 2, |
| 47 | + "attn": 8, |
| 48 | + "attn_layer": 2, |
| 49 | + "attn_dotr": True, |
| 50 | + "attn_mask": False, |
| 51 | + "set_davg_zero": True, |
| 52 | + "type_one_side": True, |
| 53 | + "seed": 1, |
| 54 | + }, |
| 55 | + "fitting_net": { |
| 56 | + "type": "ener", |
| 57 | + "neuron": [5, 5], |
| 58 | + "seed": 1, |
| 59 | + }, |
| 60 | + } |
| 61 | + |
| 62 | + |
| 63 | +@unittest.skipUnless(INSTALLED_TF2, "TF2 backend is not installed") |
| 64 | +class TestTF2ZBLModelFactory(unittest.TestCase): |
| 65 | + def test_does_not_mutate_input(self) -> None: |
| 66 | + data = _zbl_config() |
| 67 | + orig = deepcopy(data) |
| 68 | + get_zbl_model(data) |
| 69 | + self.assertEqual(data, orig) |
| 70 | + |
| 71 | + def test_injects_type_map_into_subconfigs(self) -> None: |
| 72 | + data = _zbl_config() |
| 73 | + model = get_zbl_model(data) |
| 74 | + dp_atomic = model.atomic_model.models[0] |
| 75 | + self.assertEqual(list(dp_atomic.descriptor.get_type_map()), data["type_map"]) |
| 76 | + self.assertEqual(list(dp_atomic.fitting_net.get_type_map()), data["type_map"]) |
| 77 | + |
| 78 | + |
| 79 | +if __name__ == "__main__": |
| 80 | + unittest.main() |
0 commit comments