-
Notifications
You must be signed in to change notification settings - Fork 55
Add Append MDP environment (Set Addition) and Perfect Binary Tree environment (bijection traj -> term states) #244
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
15 commits
Select commit
Hold shift + click to select a range
24918d7
Add two simple gym environments
alexandrelarouche 6bef343
Rename perfect tree
alexandrelarouche c9f559a
Reformat
alexandrelarouche 1fcb6dd
Merge branch 'GFNOrg:master' into new_envs
alexandrelarouche e918388
Merge branch 'new_envs' of github.com:alexandrelarouche/torchgfn into…
alexandrelarouche 7d87010
Pyright fix
alexandrelarouche 46bad1e
Fix branching factor for Perfect Binary Tree
alexandrelarouche c216ce6
Fix branching factor for Perfect Binary Tree
alexandrelarouche d5b0482
Merge branch 'master' into pr/alexandrelarouche/244
saleml c50b1ab
Update PerfectBinaryTree and SetAddition documentation to clarify nod…
saleml 479f535
Update documentation for PerfectBinaryTree and SetAddition to include…
saleml 82da839
Refactor PerfectBinaryTree to improve tuple handling in inverse trans…
saleml aee2cf5
Refactor reward method in SetAddition class for clarity and consisten…
saleml 993bf0f
Add tests for SetAddition and PerfectBinaryTree environments, coverin…
saleml 401f8f7
autoflake and isort
saleml 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -188,3 +188,4 @@ scripts.py | |
|
|
||
| models/ | ||
| *.DS_Store | ||
| .python-version | ||
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,123 @@ | ||
| from typing import Callable | ||
|
|
||
| import torch | ||
|
|
||
| from gfn.env import Actions, DiscreteEnv, DiscreteStates | ||
| from gfn.states import States | ||
|
|
||
|
|
||
| class PerfectBinaryTree(DiscreteEnv): | ||
| r""" | ||
| Perfect Tree Environment where there is a bijection between trajectories and terminating states. | ||
| Nodes are represented by integers, starting from 0 for the root. | ||
| States are represented by a single integer tensor corresponding to the node index. | ||
| Actions are integers: 0 (left child), 1 (right child), 2 (exit). | ||
|
|
||
| e.g.: | ||
|
|
||
| 0 (root) | ||
| / \ | ||
| 1 2 | ||
| / \ / \ | ||
| 3 4 5 6 | ||
| / \ / \ / \ / \ | ||
| 7 8 9 10 11 12 13 14 (terminating states if depth=3) | ||
|
|
||
| Recommended preprocessor: `OneHotPreprocessor`. | ||
| """ | ||
|
|
||
| def __init__(self, reward_fn: Callable, depth: int = 4): | ||
| self.reward_fn = reward_fn | ||
| self.depth = depth | ||
| self.branching_factor = 2 | ||
| self.n_actions = self.branching_factor + 1 | ||
| self.n_nodes = 2 ** (self.depth + 1) - 1 | ||
|
|
||
| self.s0 = torch.zeros((1,), dtype=torch.long) | ||
| self.sf = torch.full((1,), fill_value=-1, dtype=torch.long) | ||
| super().__init__(self.n_actions, self.s0, (1,), sf=self.sf) | ||
|
|
||
| ( | ||
| self.transition_table, | ||
| self.inverse_transition_table, | ||
| self.term_states, | ||
| ) = self._build_tree() | ||
|
|
||
| def _build_tree(self) -> tuple[dict, dict, DiscreteStates]: | ||
| """Create a transition table ensuring a bijection between trajectories and last states.""" | ||
| transition_table = {} | ||
| inverse_transition_table = {} | ||
| node_index = 0 | ||
| queue = [(node_index, 0)] # (current_node, depth) | ||
|
|
||
| terminating_states_id = set() | ||
| while queue: | ||
| node, d = queue.pop(0) | ||
| if d < self.depth: | ||
| for a in range(self.branching_factor): | ||
| node_index += 1 | ||
| transition_table[(node, a)] = node_index | ||
| inverse_transition_table[(node_index, a)] = node | ||
| queue.append((node_index, d + 1)) | ||
| else: | ||
| terminating_states_id.add(node) | ||
| terminating_states_id = torch.tensor(list(terminating_states_id)).reshape(-1, 1) | ||
| terminating_states = self.states_from_tensor(terminating_states_id) | ||
|
|
||
| return transition_table, inverse_transition_table, terminating_states | ||
|
|
||
| def backward_step(self, states: DiscreteStates, actions: Actions) -> torch.Tensor: | ||
| tuples = torch.hstack((states.tensor, actions.tensor)).tolist() | ||
| tuples = tuple((tuple_) for tuple_ in tuples) | ||
| next_states_tns = [ | ||
| self.inverse_transition_table.get(tuple(tuple_)) for tuple_ in tuples | ||
| ] | ||
| next_states_tns = torch.tensor(next_states_tns).reshape(-1, 1) | ||
| next_states_tns = torch.tensor(next_states_tns).reshape(-1, 1).long() | ||
| return next_states_tns | ||
|
|
||
| def step(self, states: DiscreteStates, actions: Actions) -> torch.Tensor: | ||
| tuples = torch.hstack((states.tensor, actions.tensor)).tolist() | ||
| tuples = tuple(tuple(tuple_) for tuple_ in tuples) | ||
| next_states_tns = [self.transition_table.get(tuple_) for tuple_ in tuples] | ||
| next_states_tns = torch.tensor(next_states_tns).reshape(-1, 1).long() | ||
| return next_states_tns | ||
|
|
||
| def update_masks(self, states: DiscreteStates) -> None: | ||
| terminating_states_mask = torch.isin( | ||
| states.tensor, self.terminating_states.tensor | ||
| ).flatten() | ||
| initial_state_mask = (states.tensor == self.s0).flatten() | ||
| even_states = (states.tensor % 2 == 0).flatten() | ||
|
|
||
| # Going from any node, we can choose action 0 or 1 | ||
| # Except terminating states where we must end the trajectory | ||
| states.forward_masks[~terminating_states_mask, -1] = False | ||
| states.forward_masks[terminating_states_mask, :] = False | ||
| states.forward_masks[terminating_states_mask, -1] = True | ||
|
|
||
| # Even states are to the right, so tied to action 1 | ||
| # Uneven states are to the left, tied to action 0 | ||
| states.backward_masks[even_states, 1] = True | ||
| states.backward_masks[even_states, 0] = False | ||
| states.backward_masks[~even_states, 1] = False | ||
| states.backward_masks[~even_states, 0] = True | ||
|
|
||
| # Initial state has no available backward action | ||
| states.backward_masks[initial_state_mask, :] = False | ||
|
|
||
| def get_states_indices(self, states: States): | ||
| return torch.flatten(states.tensor) | ||
|
|
||
| @property | ||
| def all_states(self) -> DiscreteStates: | ||
| return self.states_from_tensor(torch.arange(self.n_nodes).reshape(-1, 1)) | ||
|
|
||
| @property | ||
| def terminating_states(self) -> DiscreteStates: | ||
| lb = 2**self.depth - 1 | ||
| ub = 2 ** (self.depth + 1) - 1 | ||
| return self.make_states_class()(torch.arange(lb, ub).reshape(-1, 1)) | ||
|
|
||
| def reward(self, final_states): | ||
| return self.reward_fn(final_states.tensor) |
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,75 @@ | ||
| from typing import Callable | ||
|
|
||
| import torch | ||
|
|
||
| from gfn.env import Actions, DiscreteEnv, DiscreteStates | ||
|
|
||
|
|
||
| class SetAddition(DiscreteEnv): | ||
| """Append only MDP, similarly to what is described in Remark 8 of Shen et al. 2023 | ||
| [Towards Understanding and Improving GFlowNet Training](https://proceedings.mlr.press/v202/shen23a.html) | ||
|
|
||
| The state is a binary vector of length `n_items`, where 1 indicates the presence of an item. | ||
| Actions are integers from 0 to `n_items - 1` to add the corresponding item, or `n_items` to exit. | ||
| Adding an existing item is invalid. The trajectory must end when `max_items` are present. | ||
|
|
||
| Recommended preprocessor: `IdentityPreprocessor`. | ||
| """ | ||
|
|
||
| def __init__(self, n_items: int, max_items: int, reward_fn: Callable): | ||
| self.n_items = n_items | ||
| self.reward_fn = reward_fn | ||
| self.max_traj_len = max_items | ||
| n_actions = n_items + 1 | ||
| s0 = torch.zeros(n_items) | ||
| state_shape = (n_items,) | ||
|
|
||
| super().__init__(n_actions, s0, state_shape) | ||
|
|
||
| def get_states_indices(self, states: DiscreteStates): | ||
| states_raw = states.tensor | ||
|
|
||
| canonical_base = 2 ** torch.arange( | ||
| self.n_items - 1, -1, -1, device=states_raw.device | ||
| ) | ||
| indices = (canonical_base * states_raw).sum(-1).long() | ||
| return indices | ||
|
|
||
| def update_masks(self, states: DiscreteStates) -> None: | ||
| trajs_that_must_end = states.tensor.sum(dim=1) >= self.max_traj_len | ||
| trajs_that_may_continue = states.tensor.sum(dim=1) < self.max_traj_len | ||
|
|
||
| states.forward_masks[trajs_that_may_continue, : self.n_items] = ( | ||
| states.tensor[trajs_that_may_continue] == 0 | ||
| ) | ||
|
|
||
| # Disallow everything for trajs that must end | ||
| states.forward_masks[trajs_that_must_end, : self.n_items] = 0 | ||
| states.forward_masks[..., -1] = 1 # Allow exit action | ||
|
|
||
| states.backward_masks[..., : self.n_items] = states.tensor != 0 | ||
|
|
||
| # Disallow exit action if at s_0 | ||
| at_initial_state = torch.all(states.tensor == 0, dim=1) | ||
| states.forward_masks[at_initial_state, -1] = 0 | ||
|
|
||
| def step(self, states: DiscreteStates, actions: Actions) -> torch.Tensor: | ||
| new_states_tensor = states.tensor.scatter(-1, actions.tensor, 1, reduce="add") | ||
| return new_states_tensor | ||
|
|
||
| def backward_step(self, states: DiscreteStates, actions: Actions): | ||
| new_states_tensor = states.tensor.scatter(-1, actions.tensor, -1, reduce="add") | ||
| return new_states_tensor | ||
|
|
||
| def reward(self, final_states: DiscreteStates) -> torch.Tensor: | ||
| return self.reward_fn(final_states.tensor) | ||
|
|
||
| @property | ||
| def all_states(self) -> DiscreteStates: | ||
| digits = torch.arange(0, 2, device=self.device) | ||
| all_states = torch.cartesian_prod(*[digits] * self.n_items) | ||
| return DiscreteStates(all_states) | ||
|
|
||
| @property | ||
| def terminating_states(self) -> DiscreteStates: | ||
| return self.all_states[1:] # Remove initial state s_0 | ||
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could you please add a one or two line explanation of this environment, e.g. states, actions... ?