-
Notifications
You must be signed in to change notification settings - Fork 202
Fix SquareCBExploration.act for batched values (broadcast crash + per-row probability sum) #133
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
Osamaali313
wants to merge
2
commits into
facebookresearch:main
Choose a base branch
from
Osamaali313:fix/squarecb-batched-act
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.
Open
Changes from all commits
Commits
Show all changes
2 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| # Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| # All rights reserved. | ||
| # | ||
| # This source code is licensed under the MIT license found in the | ||
| # LICENSE file in the root directory of this source tree. | ||
| # | ||
|
|
||
| # pyre-strict | ||
|
|
||
| import unittest | ||
|
|
||
| import torch | ||
| from pearl.policy_learners.exploration_modules.contextual_bandits.squarecb_exploration import ( | ||
| FastCBExploration, | ||
| SquareCBExploration, | ||
| ) | ||
| from pearl.utils.instantiations.spaces.discrete_action import DiscreteActionSpace | ||
|
|
||
|
|
||
| class TestSquareCBExploration(unittest.TestCase): | ||
| """Tests for SquareCBExploration.act over batched value tensors.""" | ||
|
|
||
| def test_act_batched_states_does_not_crash(self) -> None: | ||
| # batch_size (2) != action_count (3) exercises the gap broadcasting: | ||
| # ``empirical_gaps = max_val.unsqueeze(1) - values`` must align the | ||
| # per-row max with the (batch_size, action_count) values. | ||
| action_space = DiscreteActionSpace( | ||
| actions=[torch.tensor([i]) for i in range(3)] | ||
| ) | ||
| exploration = SquareCBExploration(gamma=10.0) | ||
| values = torch.tensor([[0.10, 0.20, 0.90], [0.80, 0.30, 0.10]]) | ||
| torch.manual_seed(0) | ||
| actions = exploration.act( | ||
| subjective_state=torch.zeros(2, 4), | ||
| action_space=action_space, | ||
| values=values, | ||
| ) | ||
| self.assertEqual(actions.shape[0], 2) | ||
| self.assertTrue(int(actions.min()) >= 0) | ||
| self.assertTrue(int(actions.max()) < action_space.n) | ||
|
|
||
| def test_act_probabilities_are_per_row_valid_distributions(self) -> None: | ||
| # The greedy action's residual probability must be computed from the | ||
| # current row only (sum over that row), so every row of the sampling | ||
| # distribution sums to 1 and the greedy action carries the most mass. | ||
| action_space = DiscreteActionSpace( | ||
| actions=[torch.tensor([i]) for i in range(3)] | ||
| ) | ||
| exploration = SquareCBExploration(gamma=10.0) | ||
| values = torch.tensor([[0.10, 0.20, 0.90], [0.80, 0.30, 0.10]]) | ||
|
|
||
| # Reconstruct, per row, the distribution act() builds via the module's | ||
| # own get_unnormalize_prob (no randomness involved). | ||
| max_val, max_indices = torch.max(values, dim=1) | ||
| empirical_gaps = max_val.unsqueeze(1) - values | ||
| rows = [] | ||
| for b in range(values.size(0)): | ||
| prob = exploration.get_unnormalize_prob( | ||
| empirical_gaps[b, :], max_val[b], action_space.n | ||
| ) | ||
| prob[max_indices[b]] = 0.0 | ||
| prob[max_indices[b]] = 1.0 - torch.sum(prob) | ||
| rows.append(prob) | ||
| prob = torch.stack(rows) | ||
|
|
||
| self.assertTrue(torch.allclose(prob.sum(dim=1), torch.ones(2), atol=1e-6)) | ||
| # Greedy action (argmax of values) should be the most probable per row. | ||
| self.assertTrue(torch.equal(prob.argmax(dim=1), values.argmax(dim=1))) | ||
|
|
||
| def test_act_single_state(self) -> None: | ||
| action_space = DiscreteActionSpace( | ||
| actions=[torch.tensor([i]) for i in range(3)] | ||
| ) | ||
| exploration = SquareCBExploration(gamma=10.0) | ||
| torch.manual_seed(0) | ||
| action = exploration.act( | ||
| subjective_state=torch.zeros(1, 4), | ||
| action_space=action_space, | ||
| values=torch.tensor([[0.10, 0.20, 0.90]]), | ||
| ) | ||
| self.assertTrue(0 <= int(action) < action_space.n) | ||
|
|
||
| def test_fastcb_act_batched_states(self) -> None: | ||
| # FastCBExploration inherits act() and overrides get_unnormalize_prob | ||
| # with a branch on max_val; act() must therefore feed it a scalar row | ||
| # maximum so batched input does not raise on an ambiguous truth value. | ||
| action_space = DiscreteActionSpace( | ||
| actions=[torch.tensor([i]) for i in range(3)] | ||
| ) | ||
| exploration = FastCBExploration(gamma=10.0) | ||
| values = torch.tensor([[0.10, 0.20, 0.90], [0.80, 0.30, 0.10]]) | ||
| torch.manual_seed(0) | ||
| actions = exploration.act( | ||
| subjective_state=torch.zeros(2, 4), | ||
| action_space=action_space, | ||
| values=values, | ||
| ) | ||
| self.assertEqual(actions.shape[0], 2) | ||
| self.assertTrue(int(actions.min()) >= 0) | ||
| self.assertTrue(int(actions.max()) < action_space.n) |
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.
Agreed, and thanks — this is exactly right.
FastCBExplorationinherits thisactand overridesget_unnormalize_probwithif max_val <= self.reward_lb:, which raisesRuntimeError: Boolean value of Tensor with more than one value is ambiguouson a batchedmax_val(confirmed by calling it directly). I refactoredactto build the policy inside the per-row loop, passing the scalar row maximummax_val[batch_ind]and the row gapsempirical_gaps[batch_ind, :]. Results are identical forSquareCBExploration, andFastCBExplorationnow supports batched input too. Added aFastCBExplorationbatched regression test alongside the SquareCB ones.