Repository navigation
Description
Describe the bug
With a mask, Categorical.is_in and Categorical.project pass the raw value straight to mask.gather, so a value outside [0, n) raises an IndexError instead of returning False / getting clamped. The unmasked spec handles the same values fine. Masked MultiCategorical crashes the same way since it goes through Categorical.
One more in the same spot: project on a masked int32 spec crashes even for an in-range masked-out value, because the resampled index comes back as int64 (masked_scatter dtype mismatch).
This is reachable from SafeModule(..., spec=masked_spec, safe=True), which projects every policy output, so a policy that emits n or -1 crashes instead of getting a valid action.
To Reproduce
import torch
from torchrl.data import Categorical, MultiCategorical
mask = torch.tensor([True, True, False, True])
plain = Categorical(4)
masked = Categorical(4, mask=mask)
print(plain.is_in(torch.tensor(7))) # tensor(False)
print(plain.project(torch.tensor(7))) # tensor(3)
masked.is_in(torch.tensor(7)) # RuntimeError
masked.project(torch.tensor(7)) # RuntimeError
Categorical(4, mask=mask, dtype=torch.int32).project(torch.tensor(2, dtype=torch.int32)) # RuntimeError
MultiCategorical([2, 3], mask=torch.tensor([True, True, True, False, True])).is_in(torch.tensor([1, 5])) # RuntimeErrorRuntimeError: index 7 is out of bounds for dimension 0 with size 4
RuntimeError: masked_scatter: expected self and source to have same dtypes but gotInt and LongExpected behavior
Same as the unmasked spec: is_in returns False for out-of-range values, and project clamps into [0, n), then resamples if the result is masked out. project on an int32 spec should return int32.
System info
torchrl from source at main (df1db3d), torch 2.15.0, numpy 2.5.5, Python 3.12.3, Linux.
Reason and Possible fixes
In torchrl/data/tensor_specs.py, the masked branch of Categorical.is_in should check 0 <= val < n before reading the mask, and the masked branch of _project should clamp the value (like the unmasked branch) before indexing the mask, then cast the resampled values back to the spec dtype. It's a ~7 line change. I have a fix with a test and can open a PR if that sounds good.
(Not touching dtype checks in is_in, since #793 / #1952 cover that.)
Checklist
- I have checked that there is no similar issue in the repo (required)
- I have read the documentation (required)
- I have provided a minimal working example to reproduce the bug (required)
Activity