SliceSamplerWithoutReplacement¶
- class torchrl.data.replay_buffers.SliceSamplerWithoutReplacement(*, num_slices: int | None = None, slice_len: int | None = None, drop_last: bool = False, end_key: NestedKey | None = None, traj_key: NestedKey | None = None, ends: torch.Tensor | None = None, trajectories: torch.Tensor | None = None, truncated_key: NestedKey | None = ('next', 'truncated'), strict_length: bool = True, shuffle: bool = True, compile: bool | dict = False, use_gpu: bool | torch.device = False)[源代码]¶
在给定开始和停止信号的情况下,沿第一维无放回地采样数据切片。
在此上下文中,
无放回
意味着在计数器自动重置之前,同一个元素(不是轨迹)不会被重复采样。然而,在单个采样中,给定轨迹只会出现一个切片(见下面的示例)。此类应与静态回放缓冲区或在两次回放缓冲区扩展之间使用。扩展回放缓冲区将重置采样器,目前不允许连续无放回采样。
注意
SliceSamplerWithoutReplacement 在检索轨迹索引时可能很慢。为了加速其执行,优先使用 end_key 而不是 traj_key,并考虑以下关键字参数:
compile
,cache_values
和use_gpu
。- 关键字参数:
drop_last (bool, 可选) – 如果为
True
,则最后一个不完整的样本(如果存在)将被丢弃。如果为False
,则会保留最后一个样本。默认为False
。num_slices (int) – 要采样的切片数量。批量大小必须大于或等于
num_slices
参数。与slice_len
互斥。slice_len (int) – 要采样的切片长度。批量大小必须大于或等于
slice_len
参数且能被其整除。与num_slices
互斥。end_key (NestedKey, 可选) – 指示轨迹(或情节)结束的键。默认为
("next", "done")
。traj_key (NestedKey, 可选) – 指示轨迹的键。默认为
"episode"
(在 TorchRL 的数据集中常用)。ends (torch.Tensor, 可选) – 一个 1 维布尔张量,包含运行结束信号。当
end_key
或traj_key
获取成本很高,或者此信号已准备好时使用。必须与cache_values=True
一起使用,不能与end_key
或traj_key
结合使用。trajectories (torch.Tensor, 可选) – 一个 1 维整数张量,包含运行 ID。当
end_key
或traj_key
获取成本很高,或者此信号已准备好时使用。必须与cache_values=True
一起使用,不能与end_key
或traj_key
结合使用。truncated_key (NestedKey, 可选) – 如果不为
None
,此参数指示应将截断信号写入输出数据的哪个位置。这用于向值估计器指示提供的轨迹中断的位置。默认为("next", "truncated")
。此功能仅适用于TensorDictReplayBuffer
实例(否则截断键将在sample()
方法返回的 info 字典中返回)。strict_length (bool, 可选) – 如果为
False
,则允许长度小于 slice_len(或 batch_size // num_slices)的轨迹出现在批次中。如果为True
,则将过滤掉长度小于要求的轨迹。请注意,这可能导致实际 batch_size 小于请求的大小!可以使用split_trajectories()
分割轨迹。默认为True
。shuffle (bool, 可选) – 如果为
False
,则轨迹的顺序不会被打乱。默认为True
。compile (bool 或 dict of kwargs, 可选) – 如果为
True
,则sample()
方法的瓶颈部分将使用compile()
进行编译。也可以使用此参数将关键字参数传递给 torch.compile。默认为False
。use_gpu (bool 或 torch.device) – 如果为
True
(或传递了设备),则将使用加速器来检索轨迹起始点的索引。当缓冲区内容很大时,这可以显著加速采样。默认为False
。
注意
为了恢复存储中的轨迹分割,
SliceSamplerWithoutReplacement
将首先尝试在存储中查找traj_key
条目。如果找不到,将使用end_key
重建情节。示例
>>> import torch >>> from tensordict import TensorDict >>> from torchrl.data.replay_buffers import LazyMemmapStorage, TensorDictReplayBuffer >>> from torchrl.data.replay_buffers.samplers import SliceSamplerWithoutReplacement >>> >>> rb = TensorDictReplayBuffer( ... storage=LazyMemmapStorage(1000), ... # asking for 10 slices for a total of 320 elements, ie, 10 trajectories of 32 transitions each ... sampler=SliceSamplerWithoutReplacement(num_slices=10), ... batch_size=320, ... ) >>> episode = torch.zeros(1000, dtype=torch.int) >>> episode[:300] = 1 >>> episode[300:550] = 2 >>> episode[550:700] = 3 >>> episode[700:] = 4 >>> data = TensorDict( ... { ... "episode": episode, ... "obs": torch.randn((3, 4, 5)).expand(1000, 3, 4, 5), ... "act": torch.randn((20,)).expand(1000, 20), ... "other": torch.randn((20, 50)).expand(1000, 20, 50), ... }, [1000] ... ) >>> rb.extend(data) >>> sample = rb.sample() >>> # since we want trajectories of 32 transitions but there are only 4 episodes to >>> # sample from, we only get 4 x 32 = 128 transitions in this batch >>> print("sample:", sample) >>> print("trajectories in sample", sample.get("episode").unique())
SliceSamplerWithoutReplacement
与大多数 TorchRL 数据集默认兼容,并允许用户以类似数据加载器的方式使用数据集示例
>>> import torch >>> >>> from torchrl.data.datasets import RobosetExperienceReplay >>> from torchrl.data import SliceSamplerWithoutReplacement >>> >>> torch.manual_seed(0) >>> num_slices = 10 >>> dataid = list(RobosetExperienceReplay.available_datasets)[0] >>> data = RobosetExperienceReplay(dataid, batch_size=320, ... sampler=SliceSamplerWithoutReplacement(num_slices=num_slices)) >>> # the last sample is kept, since drop_last=False by default >>> for i, batch in enumerate(data): ... print(batch.get("episode").unique()) tensor([ 5, 6, 8, 11, 12, 14, 16, 17, 19, 24]) tensor([ 1, 2, 7, 9, 10, 13, 15, 18, 21, 22]) tensor([ 0, 3, 4, 20, 23])
当请求大量总样本但轨迹数量少且跨度小时,批次中每个轨迹最多只包含一个样本
示例
>>> import torch >>> from tensordict import TensorDict >>> from torchrl.collectors.utils import split_trajectories >>> from torchrl.data import ReplayBuffer, LazyTensorStorage, SliceSampler, SliceSamplerWithoutReplacement >>> >>> rb = ReplayBuffer(storage=LazyTensorStorage(max_size=1000), ... sampler=SliceSamplerWithoutReplacement( ... slice_len=5, traj_key="episode",strict_length=False ... )) ... >>> ep_1 = TensorDict( ... {"obs": torch.arange(100), ... "episode": torch.zeros(100),}, ... batch_size=[100] ... ) >>> ep_2 = TensorDict( ... {"obs": torch.arange(51), ... "episode": torch.ones(51),}, ... batch_size=[51] ... ) >>> rb.extend(ep_1) >>> rb.extend(ep_2) >>> >>> s = rb.sample(50) >>> t = split_trajectories(s, trajectory_key="episode") >>> print(t["obs"]) tensor([[14, 15, 16, 17, 18], [ 3, 4, 5, 6, 7]]) >>> print(t["episode"]) tensor([[0., 0., 0., 0., 0.], [1., 1., 1., 1., 1.]]) >>> >>> s = rb.sample(50) >>> t = split_trajectories(s, trajectory_key="episode") >>> print(t["obs"]) tensor([[ 4, 5, 6, 7, 8], [26, 27, 28, 29, 30]]) >>> print(t["episode"]) tensor([[0., 0., 0., 0., 0.], [1., 1., 1., 1., 1.]])