-
Notifications
You must be signed in to change notification settings - Fork 7
Feat: Add new efficiency test #264
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
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
4daeebc
feat: add new efficiency test
anyangml 17a7897
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 3a9c0ae
fix: precommit
anyangml 0c52c58
chore: remove redundant
anyangml e25bbb3
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 789a688
feat: add UT for binary search
anyangml f354aaf
fix typo
caic99 8344dcc
Update efficiency_utils.py
caic99 342c91d
feat: move binary search to frame level
anyangml 9b9c736
fix: typo
anyangml b4cac25
feat: update efficiency test data
anyangml c7e4b9c
Merge branch 'main' into feat/redesign-efficiency-tests
anyangml 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
100 changes: 100 additions & 0 deletions
100
lambench/tasks/calculator/inference_efficiency/efficiency_utils.py
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,100 @@ | ||
from ase.atoms import Atoms | ||
from lambench.models.ase_models import ASEModel | ||
import numpy as np | ||
import math | ||
|
||
|
||
def get_efv(atoms: Atoms) -> tuple[float, np.ndarray, np.ndarray]: | ||
""" | ||
Perform force field prediction for one system, return energy, forces and stress. | ||
""" | ||
e = atoms.get_potential_energy() | ||
f = atoms.get_forces() | ||
stress = atoms.get_stress() | ||
v = ( | ||
-np.array( | ||
[ | ||
[stress[0], stress[5], stress[4]], | ||
[stress[5], stress[1], stress[3]], | ||
[stress[4], stress[3], stress[2]], | ||
] | ||
) | ||
* atoms.get_volume() | ||
) | ||
return e, f, v | ||
|
||
|
||
def catch_oom_error(atoms: Atoms) -> bool: | ||
""" | ||
Catch OOM error when running inference. | ||
""" | ||
try: | ||
get_efv(atoms) | ||
return False | ||
except Exception as e: | ||
if "out of memory" in str(e) or "OOM" in str(e): | ||
return True | ||
else: | ||
return False | ||
|
||
|
||
def get_divisors(num: int) -> list[int]: | ||
divisors = set() | ||
for i in range(1, int(math.isqrt(num)) + 1): | ||
if num % i == 0: | ||
divisors.add(i) | ||
divisors.add(num // i) | ||
return sorted(divisors) | ||
|
||
|
||
def find_even_factors(num: int) -> tuple[int, int, int]: | ||
""" | ||
Find three factors of a number that are as evenly distributed as possible. | ||
The function returns a tuple of three factors (a, b, c) such that a * b * c = num. | ||
The factors are sorted in ascending order (a <= b <= c). | ||
""" | ||
divisors = get_divisors(num) | ||
best = None | ||
min_spread = float("inf") | ||
|
||
for a in divisors: | ||
num_div_a = num // a | ||
divisors_b = get_divisors(num_div_a) | ||
|
||
# Since a <= b <= c, no need to consider b < a | ||
for b in divisors_b: | ||
if b < a: | ||
continue | ||
c = num_div_a // b | ||
if a * b * c == num: | ||
factors = [a, b, c] | ||
spread = max(factors) - min(factors) | ||
if spread < min_spread: | ||
min_spread = spread | ||
best = (a, b, c) | ||
if spread == 0: # Perfect distribution found | ||
return best | ||
return best | ||
|
||
|
||
def binary_search_max_natoms( | ||
model: ASEModel, atoms: Atoms, upper_limit: int = 1000, max_iterations: int = 15 | ||
) -> int: | ||
""" | ||
Binary search for the maximum number of atoms that can be processed by the model. | ||
|
||
""" | ||
low, high, iteration = 1, upper_limit, 0 | ||
while low < high and iteration < max_iterations: | ||
mid = (low + high + 1) // 2 | ||
scaling_factor = np.int32(np.ceil(mid / len(atoms))) | ||
scaled_atoms = atoms.copy() | ||
a, b, c = find_even_factors(scaling_factor) | ||
scaled_atoms = scaled_atoms.repeat((a, b, c)) | ||
scaled_atoms.calc = model.calc | ||
if catch_oom_error(scaled_atoms): | ||
high = mid - 1 | ||
else: | ||
low = mid | ||
iteration += 1 | ||
return low |
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,53 @@ | ||
from lambench.tasks.calculator.inference_efficiency.efficiency_utils import ( | ||
find_even_factors, | ||
binary_search_max_natoms, | ||
) | ||
import pytest | ||
import numpy as np | ||
from ase.atoms import Atoms | ||
from unittest.mock import MagicMock | ||
|
||
OOM_TEST_ATOM = Atoms( | ||
symbols="Mg", | ||
pbc=True, | ||
cell=[ | ||
[-2.244256, -2.244256, 0.0], | ||
[-2.244256, 0.0, -2.244256], | ||
[0.0, -2.244256, -2.244256], | ||
], | ||
positions=[ | ||
[0, 0, 0], | ||
], | ||
) # mp-1056702 | ||
|
||
|
||
@pytest.mark.parametrize( | ||
"num, expected", | ||
[ | ||
(27, (3, 3, 3)), # Perfect cube | ||
(13, (1, 1, 13)), # Prime number | ||
(16, (2, 2, 4)), # Even number | ||
(728, (7, 8, 13)), # Large number | ||
], | ||
) | ||
def test_find_even_factors(num, expected): | ||
result = find_even_factors(num) | ||
assert result == expected, f"Expected {expected}, got {result}" | ||
|
||
|
||
@pytest.mark.parametrize( | ||
"threshold, max_natoms", | ||
[(1999, 1000), (247, 247), (121, 121), (100, 100), (38, 38), (31, 31)], | ||
) | ||
def test_binary_search_max_natoms(threshold, max_natoms): | ||
def mock_get_potential_energy(atoms=None): | ||
if len(atoms) > threshold: | ||
raise MemoryError("OOM: Too many atoms!") | ||
return np.random.rand() | ||
|
||
mock_model = MagicMock() | ||
mock_model.calc = MagicMock() | ||
mock_model.calc.get_potential_energy.side_effect = mock_get_potential_energy | ||
|
||
result = binary_search_max_natoms(mock_model, OOM_TEST_ATOM) | ||
assert result == max_natoms, f"Expected {max_natoms}, got {result}" |
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.