-
Notifications
You must be signed in to change notification settings - Fork 10
feat(rewards): add a prepare hook to the reward protocol and scalers #373
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
Draft
manzuoni-astera
wants to merge
3
commits into
diff-use:main
Choose a base branch
from
manzuoni-astera:michaelanzuoni/reward-prepare-hook
base: main
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.
Draft
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
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,91 @@ | ||
| """Tests for the two-phase reward preparation hook.""" | ||
|
|
||
| import torch | ||
| from biotite.structure import AtomArray | ||
| from sampleworks.core.rewards.protocol import ( | ||
| PreparableRewardFunctionProtocol, | ||
| prepare_reward_if_needed, | ||
| RewardFunctionProtocol, | ||
| ) | ||
|
|
||
|
|
||
| class PlainReward: | ||
| """Reward that is fully configured at construction time.""" | ||
|
|
||
| def __call__( | ||
| self, | ||
| coordinates: torch.Tensor, | ||
| elements: torch.Tensor | None = None, | ||
| b_factors: torch.Tensor | None = None, | ||
| occupancies: torch.Tensor | None = None, | ||
| unique_combinations: torch.Tensor | None = None, | ||
| inverse_indices: torch.Tensor | None = None, | ||
| ) -> torch.Tensor: | ||
| return (coordinates**2).sum() | ||
|
|
||
|
|
||
| class PreparableReward(PlainReward): | ||
| """Reward that binds to the model topology, recording what it was given.""" | ||
|
|
||
| def __init__(self): | ||
| self.prepared_with: list[tuple[int, str]] = [] | ||
| self.calls_before_prepare = 0 | ||
|
|
||
| def prepare(self, atom_array: AtomArray, *, device: torch.device | str = "cpu") -> None: | ||
| """Record the topology and device this reward was bound to.""" | ||
| self.prepared_with.append((atom_array.array_length(), str(device))) | ||
|
|
||
| def __call__(self, coordinates: torch.Tensor, *args, **kwargs) -> torch.Tensor: | ||
| if not self.prepared_with: | ||
| self.calls_before_prepare += 1 | ||
| return super().__call__(coordinates) | ||
|
|
||
|
|
||
| def make_atom_array(n_atoms: int = 4) -> AtomArray: | ||
| """Build a minimal AtomArray of carbons at the origin.""" | ||
| atom_array = AtomArray(n_atoms) | ||
| atom_array.coord = torch.zeros(n_atoms, 3).numpy() | ||
| atom_array.element = ["C"] * n_atoms | ||
| return atom_array | ||
|
|
||
|
|
||
| def test_preparable_reward_satisfies_both_protocols(): | ||
| """A reward with prepare() is still an ordinary reward function.""" | ||
| reward = PreparableReward() | ||
|
|
||
| assert isinstance(reward, RewardFunctionProtocol) | ||
| assert isinstance(reward, PreparableRewardFunctionProtocol) | ||
|
|
||
|
|
||
| def test_plain_reward_is_not_preparable(): | ||
| """Structural typing must not classify every reward as two-phase.""" | ||
| assert not isinstance(PlainReward(), PreparableRewardFunctionProtocol) | ||
|
|
||
|
|
||
| def test_prepare_hook_forwards_atom_array_and_device(): | ||
| """The reward is bound to the atom array and device the caller passed.""" | ||
| reward = PreparableReward() | ||
| atom_array = make_atom_array(7) | ||
|
|
||
| prepare_reward_if_needed(reward, atom_array, device=torch.device("cpu")) | ||
|
|
||
| assert reward.prepared_with == [(7, "cpu")] | ||
|
|
||
|
|
||
| def test_prepare_hook_is_a_no_op_for_rewards_that_do_not_need_it(): | ||
| """Callers can prepare unconditionally, so one-phase rewards must be untouched.""" | ||
| reward = PlainReward() | ||
|
|
||
| prepare_reward_if_needed(reward, make_atom_array(), device="cpu") | ||
|
|
||
| assert reward(torch.ones(1, 4, 3)) == 12.0 | ||
|
|
||
|
|
||
| def test_prepare_is_rerunnable_for_a_new_topology(): | ||
| """Preparing again rebinds, so a reward can move between topologies or devices.""" | ||
| reward = PreparableReward() | ||
|
|
||
| prepare_reward_if_needed(reward, make_atom_array(3), device="cpu") | ||
| prepare_reward_if_needed(reward, make_atom_array(5), device="cpu") | ||
|
|
||
| assert reward.prepared_with == [(3, "cpu"), (5, "cpu")] | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
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
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.