-
Notifications
You must be signed in to change notification settings - Fork 635
fix(dpmodel): materialize fitting buffers on active backend #5841
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
njzjz-bot
wants to merge
3
commits into
deepmodeling:master
Choose a base branch
from
njzjz-bot:fix/dpmodel-general-fitting-buffers-5642
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| # SPDX-License-Identifier: LGPL-3.0-or-later | ||
| """Backend-boundary regressions for dpmodel polarizability fitting.""" | ||
|
|
||
| import unittest | ||
|
|
||
| import numpy as np | ||
|
|
||
| try: | ||
| import torch | ||
| except ImportError: | ||
| torch = None | ||
|
|
||
| from deepmd.dpmodel.fitting.polarizability_fitting import ( | ||
| PolarFitting, | ||
| ) | ||
|
|
||
|
|
||
| class TestPolarFittingBackendBuffers(unittest.TestCase): | ||
| """Keep portable polar buffers compatible with backend-native inputs.""" | ||
|
|
||
| @unittest.skipIf(torch is None, "PyTorch is not installed") | ||
| def test_scale_and_shift_follow_torch_prediction(self) -> None: | ||
| fitting = PolarFitting( | ||
| ntypes=2, | ||
| dim_descrpt=3, | ||
| embedding_width=2, | ||
| neuron=[5, 5], | ||
| precision="float64", | ||
| mixed_types=True, | ||
| fit_diag=True, | ||
| scale=[1.5, 0.25], | ||
| shift_diag=True, | ||
| seed=20260717, | ||
| ) | ||
| fitting.constant_matrix[:] = [0.75, -0.5] | ||
|
|
||
| descriptor = np.array([[[0.2, -0.1, 0.4], [0.5, 0.3, -0.2]]], dtype=np.float64) | ||
| atype = np.array([[0, 1]], dtype=np.int64) | ||
| rotation = np.array( | ||
| [ | ||
| [ | ||
| [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], | ||
| [[0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], | ||
| ] | ||
| ], | ||
| dtype=np.float64, | ||
| ) | ||
| expected = fitting(descriptor, atype, gr=rotation)["polarizability"] | ||
|
|
||
| result = fitting( | ||
| torch.as_tensor(descriptor), | ||
| torch.as_tensor(atype), | ||
| gr=torch.as_tensor(rotation), | ||
| )["polarizability"] | ||
|
|
||
| self.assertIsInstance(result, torch.Tensor) | ||
| self.assertEqual(result.dtype, torch.float64) | ||
| self.assertEqual(result.device.type, "cpu") | ||
| np.testing.assert_allclose(result.detach().cpu().numpy(), expected) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,117 @@ | ||
| # SPDX-License-Identifier: LGPL-3.0-or-later | ||
| import unittest | ||
|
|
||
| import array_api_compat | ||
| import numpy as np | ||
| from jax import ( | ||
| tree_util, | ||
| ) | ||
|
|
||
| from deepmd.jax.env import ( | ||
| jnp, | ||
| nnx, | ||
| ) | ||
| from deepmd.jax.fitting.fitting import ( | ||
| EnergyFittingNet, | ||
| ) | ||
|
|
||
|
|
||
| class TestJAXFitting(unittest.TestCase): | ||
| def test_runtime_buffers_support_nnx_jit_and_grad_tracing(self) -> None: | ||
| """Portable fitting buffers must remain usable inside JAX tracing.""" | ||
| fitting = EnergyFittingNet( | ||
| ntypes=2, | ||
| dim_descrpt=3, | ||
| neuron=[5, 5], | ||
| numb_fparam=2, | ||
| numb_aparam=1, | ||
| dim_case_embd=2, | ||
| default_fparam=[0.5, -0.25], | ||
| precision="float32", | ||
| mixed_types=True, | ||
| seed=20260724, | ||
| ) | ||
| # Non-default values ensure every portable buffer contributes to the | ||
| # traced result instead of being optimized away as an all-zero no-op. | ||
| buffer_values = { | ||
| "bias_atom_e": np.array([[1.5], [-0.75]], dtype=np.float32), | ||
| "fparam_avg": np.array([0.1, -0.2], dtype=np.float32), | ||
| "fparam_inv_std": np.array([2.0, 0.5], dtype=np.float32), | ||
| "aparam_avg": np.array([0.25], dtype=np.float32), | ||
| "aparam_inv_std": np.array([4.0], dtype=np.float32), | ||
| "case_embd": np.array([0.3, -0.6], dtype=np.float32), | ||
| "default_fparam_tensor": np.array([0.5, -0.25], dtype=np.float32), | ||
| } | ||
| for name, value in buffer_values.items(): | ||
| fitting[name] = value | ||
|
|
||
| descriptor = jnp.asarray( | ||
| [[[0.2, -0.1, 0.4], [0.5, 0.3, -0.2], [-0.4, 0.7, 0.1]]], | ||
| dtype=jnp.float32, | ||
| ) | ||
| atype = jnp.asarray([[0, 1, 0]], dtype=jnp.int32) | ||
| aparam = jnp.asarray([[[0.5], [0.0], [1.0]]], dtype=jnp.float32) | ||
|
|
||
| @nnx.jit | ||
| def forward(model, descriptor, atype, aparam): | ||
| return model(descriptor, atype, aparam=aparam)["energy"] | ||
|
|
||
| @nnx.jit | ||
| def grad(model, descriptor, atype, aparam): | ||
| def loss(model): | ||
| return jnp.sum(model(descriptor, atype, aparam=aparam)["energy"]) | ||
|
|
||
| return nnx.grad(loss)(model) | ||
|
|
||
| buffer_snapshots = { | ||
| name: ( | ||
| fitting[name], | ||
| type(fitting[name]), | ||
| array_api_compat.array_namespace(fitting[name]), | ||
| np.asarray(fitting[name]).copy(), | ||
| ) | ||
| for name in buffer_values | ||
| } | ||
|
|
||
| out = forward(fitting, descriptor, atype, aparam) | ||
| grad_state = grad(fitting, descriptor, atype, aparam) | ||
| grad_leaves = [np.asarray(leaf) for leaf in tree_util.tree_leaves(grad_state)] | ||
| self.assertEqual(tuple(out.shape), (1, 3, 1)) | ||
| self.assertFalse(np.any(np.isnan(np.asarray(out)))) | ||
| self.assertTrue(grad_leaves) | ||
| self.assertTrue(all(np.all(np.isfinite(leaf)) for leaf in grad_leaves)) | ||
|
|
||
| # Tracing may read portable buffers, but it must not replace their NNX | ||
| # variables, change their array namespace, or mutate their values. | ||
| for name, ( | ||
| original, | ||
| original_type, | ||
| namespace, | ||
| values, | ||
| ) in buffer_snapshots.items(): | ||
| current = fitting[name] | ||
| self.assertIs(current, original) | ||
| self.assertIs(type(current), original_type) | ||
| self.assertIs(array_api_compat.array_namespace(current), namespace) | ||
| np.testing.assert_array_equal(np.asarray(current), values) | ||
|
|
||
| neutral_values = { | ||
| "bias_atom_e": np.zeros((2, 1), dtype=np.float32), | ||
| "fparam_avg": np.zeros(2, dtype=np.float32), | ||
| "fparam_inv_std": np.ones(2, dtype=np.float32), | ||
| "aparam_avg": np.zeros(1, dtype=np.float32), | ||
| "aparam_inv_std": np.ones(1, dtype=np.float32), | ||
| "case_embd": np.zeros(2, dtype=np.float32), | ||
| "default_fparam_tensor": np.zeros(2, dtype=np.float32), | ||
| } | ||
| baseline = np.asarray(out) | ||
| for name, neutral in neutral_values.items(): | ||
| with self.subTest(buffer=name): | ||
| fitting[name] = neutral | ||
| changed = np.asarray(forward(fitting, descriptor, atype, aparam)) | ||
| self.assertFalse(np.allclose(changed, baseline)) | ||
| fitting[name] = buffer_values[name] | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.