Repository navigation
[BugFix] Make MultiCategorical.to_one_hot accept a batched spec and the scalar sample of a shape [1] spec - #4504
Merged
bsprenger merged 4 commits intoOct 7, 2026
Conversation
Sync main with upstream
…s along the last nvec dim
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/rl/4504
Note: Links to docs will display an error until the docs builds have been completed. ❌ 8 New FailuresAs of commit ae18f27 with merge base b8b6f0c ( NEW FAILURES - The following jobs have failed:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This was referenced Oct 3, 2026
bsprenger
self-requested a review
October 4, 2026 15:33
bsprenger
requested changes
Oct 4, 2026
bsprenger
left a comment
Collaborator
There was a problem hiding this comment.
Thanks for tackling this! Let's make sure we add support for heterogeneous specs though, I am not currently seeing a reason to disallow them
…ted tensor, as its stacked one-hot spec samples
Nicholas022400701
marked this pull request as ready for review
October 4, 2026 18:33
bsprenger
approved these changes
Oct 7, 2026
bsprenger
left a comment
Collaborator
There was a problem hiding this comment.
LGTM, I added one additional test case.
In the future, let's also avoid putting so many inline comments. They bloat the diff, and generally we should strive for the code to be self-explanatory. A comment is more useful if it explains why we do something, rather than what the code is doing.
bsprenger
added a commit
that referenced
this pull request
Oct 9, 2026
…he scalar sample of a shape [1] spec (#4504) Co-authored-by: Ben Sprenger <bensprenger1999@gmail.com>
3 tasks done
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Description
MultiCategorical.to_one_hot(torchrl/data/tensor_specs.py) iteratesfor i, n in enumerate(self.nvec). For a spec with batch dims (MultiCategorical([3, 2], shape=(4, 2)), whatenv.action_speclooks like for a batched env or afterspec.expand(...))nvechas shape(4, 2),nis a row andone_hot(val[..., i], n)raisesTypeError: one_hot(): argument 'num_classes' (position 2) must be int, not Tensor.rand,is_in,to_one_hot_specandMultiOneHot.to_categoricalall handle the batched spec, so the conversion worked in one direction only. Second path:MultiCategorical([5])has shape[1]andremove_singleton=True, sorand()is a scalar andto_one_hot(scalar)raisesIndexError: too many indices for tensor of dimension 0.The widths now come from the last dim of
nvec(nvec.flatten(0, -2)[0], the reduction_split_selfuses) and a scalarvalis unsqueezed first, asis_inand_projectdo.Rows with different widths (
MultiCategorical([[2, 4], [3, 2]]), #2486) followto_one_hot_spec, which stacks such rows into aStackedMultiOneHotwhose samples are nested tensors:to_one_hotencodes each row with its own row spec and returnstorch.nested.nested_tensorof the rows, sospec.to_one_hot_spec().is_in(spec.to_one_hot(val))holds there too. Rows that are homogeneous below the first dim encode to dense entries ([[[3, 2], [3, 2]], [[4, 5], [4, 5]]]gives entries of shape(2, 5)and(2, 9)). A value with extra leading dims, and rows that differ beyond the first dim, raise theRuntimeErrorof the stacked spec'srand("Cannot create a nested tensor with a stack dimension other than 0"), since no nested tensor along dim 0 exists for them. Review round 1 asked for this instead of theValueErrorthe first push raised.Tests:
test_multi_discrete_conversion_batched_spec(nvec[5]and[5, 2, 3], spec shapes[3]and[4, 5], both conversion directions) andtest_multi_discrete_conversion_singletonfail onmain(4TypeError, 1IndexError);test_multi_discrete_conversion_heterogeneous(rows[2, 4]and[3, 2], with and without a batch dim of 3) checks the nested result against the stacked spec'sis_in, each entry against its row spec's encoding, and the two error cases.pytest test/test_specs.py: 1805 passed, 9 skipped.black22.3.0,usort1.0.3 andflake8clean. The heterogeneous test filters torch's one-time "nested tensors are in prototype stage" warning inside the test, the module turns warnings into errors and a function-levelfilterwarningsmark does not override that.#4517 also addresses the heterogeneous rows of #2486.
Motivation and Context
Fixes #4493. Every other method of the spec already supports the batched spec;
to_one_hotwas the one that did not.Types of changes
Checklist
AI disclosure: I used an AI coding agent to help write this patch, the tests and this description. I have read the change and the tests myself and I will answer review comments personally.