Skip to content

[BUG] RandomCropTensorDict never samples the last window and fails when the length equals sub_seq_len #4577

Open

Description

@jackiectl2

Describe the bug

RandomCropTensorDict samples the window start with torch.randint(max_idx_0, ...), which draws from [0, max_idx_0). The last valid window is never sampled, and when the sequence length equals sub_seq_len the call fails, although the length check accepts that case. The masked path has the same off-by-one: floor(rand * (L - sub_seq_len)) never reaches L - sub_seq_len.

To Reproduce

import torch
from tensordict import TensorDict
from torchrl.envs.transforms import RandomCropTensorDict

td = TensorDict({"a": torch.arange(4).expand(1000, 4)}, [1000, 4])
print(set(RandomCropTensorDict(2)(td)["a"][:, 0].tolist()))  # {0, 1}, never 2
RandomCropTensorDict(4)(td)  # RuntimeError: random_ expects 'from' to be less than 'to'

Expected behavior

Window starts are drawn uniformly from [0, L - sub_seq_len], both ends included, with and without mask_key.

Versions

torchrl main (264a3c2), tensordict 0.14.2, torch 2.14.1 (CPU), Python 3.12.

I have a fix with tests ready and will open a PR.

Activity

  1. jackiectl2 commented on Oct 16, 2026

    @jackiectl2
    Author

    /assign

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions