VD4RLExperienceReplay¶
- class torchrl.data.datasets.VD4RLExperienceReplay(dataset_id, batch_size: int, *, root: str | Path | None = None, download: bool = True, sampler: Sampler | None = None, writer: Writer | None = None, collate_fn: Callable | None = None, pin_memory: bool = False, prefetch: int | None = None, transform: 'torchrl.envs.Transform' | None = None, split_trajs: bool = False, totensor: bool = True, image_size: int | List[int] | None = None, num_workers: int = 0, **env_kwargs)[source]¶
V-D4RL 經驗回放資料集。
此類別會從 V-D4RL 下載 H5/npz 數據,並將其處理為 mmap 格式,從而加快索引(以及取樣)速度。
在此處了解更多關於 V-D4RL 的資訊:https://arxiv.org/abs/2206.04779
“pixels” 條目位於資料的根目錄,所有非 reward、done-state、action 或 pixels 的數據都會移至 “state” 節點下。
資料格式遵循 TED 慣例。
- 參數:
dataset_id (str) – 要下載的資料集。必須是 VD4RLExperienceReplay.available_datasets 的一部分。
batch_size (int) – 取樣期間使用的批次大小。如有必要,可以被 data.sample(batch_size) 覆蓋。
- 關鍵字參數:
root (Path 或 str, optional) – V-D4RL 資料集根目錄。實際的資料集記憶體映射檔案將儲存在 <root>/<dataset_id> 下。如果未提供,則預設為 ``~/.cache/torchrl/vd4rl`。
download (bool 或 str, optional) – 如果找不到資料集,是否應該下載。預設為
True
。下載也可以作為"force"
傳遞,在這種情況下,下載的資料將被覆蓋。sampler (Sampler, optional) – 要使用的取樣器。如果未提供,將使用預設的 RandomSampler()。
writer (Writer, optional) – 要使用的寫入器。如果未提供,將使用預設的
ImmutableDatasetWriter
。collate_fn (callable, optional) – 合併樣本列表以形成 Tensor(s)/輸出的迷你批次。從地圖樣式資料集使用批次載入時使用。
pin_memory (bool) – 是否應該在 rb 樣本上呼叫 pin_memory()。
prefetch (int, optional) – 使用多執行緒預取的下一個批次的數量。
transform (Transform, optional) – 呼叫 sample() 時要執行的轉換。要鏈式轉換,請使用
Compose
類別。split_trajs (bool, optional) – 若為
True
,軌跡將沿著第一個維度分割,並進行填充以使其形狀一致。為了分割軌跡,將使用"done"
訊號,該訊號可透過done = truncated | terminated
回復。換句話說,任何truncated
或terminated
訊號都被視為軌跡的結束。對於來自D4RL
的某些數據集,這可能不成立。使用者有責任針對split_trajs
的使用做出準確的選擇。預設值為False
。totensor (bool, optional) – 若為
True
,ToTensorImage
轉換將包含在轉換列表中(如果沒有自動偵測到)。預設值為True
。image_size (int, list of ints or None) – 若不為
None
,此參數將用於建立一個Resize
轉換,並將其附加到轉換列表中。支援 int 類型(正方形調整大小)或 int 的列表/元組(矩形調整大小)。預設值為None
(不調整大小)。num_workers (int, optional) – 下載檔案的工作人員數量。預設值為
0
(不使用多進程)。
- 變數:
available_datasets – 可下載的接受條目列表。這些名稱對應於 huggingface 數據集儲存庫中的目錄路徑。如果可能,將從 huggingface 動態檢索列表。如果沒有網路連線,將使用快取的版本。
注意
由於並非所有經驗回放都有開始和停止訊號,因此我們不會在檢索到的數據集中標記 episode。
範例
>>> import torch >>> torch.manual_seed(0) >>> from torchrl.data.datasets import VD4RLExperienceReplay >>> d = VD4RLExperienceReplay("main/walker_walk/random/64px", batch_size=32, ... image_size=50) >>> for batch in d: ... break >>> print(batch) TensorDict( fields={ action: Tensor(shape=torch.Size([32, 6]), device=cpu, dtype=torch.float32, is_shared=False), done: Tensor(shape=torch.Size([32, 1]), device=cpu, dtype=torch.bool, is_shared=False), index: Tensor(shape=torch.Size([32]), device=cpu, dtype=torch.int64, is_shared=False), is_init: Tensor(shape=torch.Size([32]), device=cpu, dtype=torch.bool, is_shared=False), next: TensorDict( fields={ done: Tensor(shape=torch.Size([32, 1]), device=cpu, dtype=torch.bool, is_shared=False), observation: TensorDict( fields={ height: Tensor(shape=torch.Size([32]), device=cpu, dtype=torch.float32, is_shared=False), orientations: Tensor(shape=torch.Size([32, 14]), device=cpu, dtype=torch.float32, is_shared=False), velocity: Tensor(shape=torch.Size([32, 9]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([32]), device=cpu, is_shared=False), pixels: Tensor(shape=torch.Size([32, 3, 50, 50]), device=cpu, dtype=torch.float32, is_shared=False), reward: Tensor(shape=torch.Size([32, 1]), device=cpu, dtype=torch.float32, is_shared=False), terminated: Tensor(shape=torch.Size([32, 1]), device=cpu, dtype=torch.bool, is_shared=False), truncated: Tensor(shape=torch.Size([32, 1]), device=cpu, dtype=torch.bool, is_shared=False)}, batch_size=torch.Size([32]), device=cpu, is_shared=False), observation: TensorDict( fields={ height: Tensor(shape=torch.Size([32]), device=cpu, dtype=torch.float32, is_shared=False), orientations: Tensor(shape=torch.Size([32, 14]), device=cpu, dtype=torch.float32, is_shared=False), velocity: Tensor(shape=torch.Size([32, 9]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([32]), device=cpu, is_shared=False), pixels: Tensor(shape=torch.Size([32, 3, 50, 50]), device=cpu, dtype=torch.float32, is_shared=False), terminated: Tensor(shape=torch.Size([32, 1]), device=cpu, dtype=torch.bool, is_shared=False), truncated: Tensor(shape=torch.Size([32, 1]), device=cpu, dtype=torch.bool, is_shared=False)}, batch_size=torch.Size([32]), device=cpu, is_shared=False)
- add(data: TensorDictBase) int ¶
將單一元素新增到回放緩衝區。
- 參數:
data (Any) – 要新增到回放緩衝區的資料
- 回傳:
資料在回放緩衝區中的索引位置。
- append_transform(transform: Transform, *, invert: bool = False) ReplayBuffer ¶
在結尾附加轉換。
當呼叫 sample 時,轉換會依序應用。
- 參數:
transform (Transform) – 要附加的轉換
- 關鍵字參數:
invert (bool, optional) – 若為
True
,轉換將會反轉(在寫入期間呼叫 forward,在讀取期間呼叫 inverse)。預設值為False
。
範例
>>> rb = ReplayBuffer(storage=LazyMemmapStorage(10), batch_size=4) >>> data = TensorDict({"a": torch.zeros(10)}, [10]) >>> def t(data): ... data += 1 ... return data >>> rb.append_transform(t, invert=True) >>> rb.extend(data) >>> assert (data == 1).all()
- property data_path¶
資料集的路徑,包括分割。
- property data_path_root¶
資料集根目錄的路徑。
- delete()¶
從磁碟刪除資料集儲存。
- dumps(path)¶
將回放緩衝區儲存到指定路徑的磁碟上。
- 參數:
path (Path or str) – 要儲存回放緩衝區的路徑。
範例
>>> import tempfile >>> import tqdm >>> from torchrl.data import LazyMemmapStorage, TensorDictReplayBuffer >>> from torchrl.data.replay_buffers.samplers import PrioritizedSampler, RandomSampler >>> import torch >>> from tensordict import TensorDict >>> # Build and populate the replay buffer >>> S = 1_000_000 >>> sampler = PrioritizedSampler(S, 1.1, 1.0) >>> # sampler = RandomSampler() >>> storage = LazyMemmapStorage(S) >>> rb = TensorDictReplayBuffer(storage=storage, sampler=sampler) >>> >>> for _ in tqdm.tqdm(range(100)): ... td = TensorDict({"obs": torch.randn(100, 3, 4), "next": {"obs": torch.randn(100, 3, 4)}, "td_error": torch.rand(100)}, [100]) ... rb.extend(td) ... sample = rb.sample(32) ... rb.update_tensordict_priority(sample) >>> # save and load the buffer >>> with tempfile.TemporaryDirectory() as tmpdir: ... rb.dumps(tmpdir) ... ... sampler = PrioritizedSampler(S, 1.1, 1.0) ... # sampler = RandomSampler() ... storage = LazyMemmapStorage(S) ... rb_load = TensorDictReplayBuffer(storage=storage, sampler=sampler) ... rb_load.loads(tmpdir) ... assert len(rb) == len(rb_load)
- empty()¶
清空回放緩衝區並將游標重設為 0。
- extend(tensordicts: TensorDictBase) Tensor ¶
使用可迭代物件中包含的一個或多個元素擴展回放緩衝區。
如果存在,將呼叫反向轉換。`
- 參數:
data (iterable) – 要加入到回放緩衝區的資料集合 (iterable)。
- 回傳:
加入到回放緩衝區的資料索引。
警告
當處理數值列表時,
extend()
可能會有不明確的簽名。數值列表應該被解釋為 PyTree (在這種情況下,列表中的所有元素都會被放入儲存在儲存中的 PyTree 的一個切片中),或是要一次新增一個數值的列表。為了解決這個問題,TorchRL 明確區分了 list 和 tuple:tuple 會被視為 PyTree,而 list(在根層級)會被解釋為要一次新增到緩衝區的一疊數值。對於ListStorage
實例,只能提供未綁定的元素(沒有 PyTrees)。
- insert_transform(index: int, transform: Transform, *, invert: bool = False) ReplayBuffer ¶
插入轉換。
當調用 sample 時,轉換會依序執行。
- 參數:
index (int) – 插入轉換的位置。
transform (Transform) – 要附加的轉換
- 關鍵字參數:
invert (bool, optional) – 若為
True
,轉換將會反轉(在寫入期間呼叫 forward,在讀取期間呼叫 inverse)。預設值為False
。
- loads(path)¶
載入給定路徑上的回放緩衝區狀態。
緩衝區應該具有匹配的元件,並且應該使用
dumps()
來儲存。- 參數:
path (Path 或 str) – 回放緩衝區儲存的路徑。
更多資訊請參考
dumps()
。
- preprocess(fn: Callable[[TensorDictBase], TensorDictBase], dim: int = 0, num_workers: int | None = None, *, chunksize: int | None = None, num_chunks: int | None = None, pool: mp.Pool | None = None, generator: torch.Generator | None = None, max_tasks_per_child: int | None = None, worker_threads: int = 1, index_with_generator: bool = False, pbar: bool = False, mp_start_method: str | None = None, num_frames: int | None = None, dest: str | Path) TensorStorage ¶
預處理資料集並傳回具有格式化資料的新儲存空間。
資料轉換必須是單一的(針對資料集的單個樣本進行操作)。
Args 和 Keyword Args 會被轉發到
map()
。隨後可以使用
delete()
刪除資料集。- 關鍵字參數:
dest (路徑 或 等效路徑) – 新資料集位置的路徑。
num_frames (int, 選填) – 如果提供,則只會轉換前 num_frames 個影格。這對於首先除錯轉換很有用。
傳回值:一個新的儲存空間,將在
ReplayBuffer
實例中使用。範例
>>> from torchrl.data.datasets import MinariExperienceReplay >>> >>> data = MinariExperienceReplay( ... list(MinariExperienceReplay.available_datasets)[0], ... batch_size=32 ... ) >>> print(data) MinariExperienceReplay( storages=TensorStorage(TensorDict( fields={ action: MemoryMappedTensor(shape=torch.Size([1000000, 8]), device=cpu, dtype=torch.float32, is_shared=True), episode: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.int64, is_shared=True), info: TensorDict( fields={ distance_from_origin: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), forward_reward: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), goal: MemoryMappedTensor(shape=torch.Size([1000000, 2]), device=cpu, dtype=torch.float64, is_shared=True), qpos: MemoryMappedTensor(shape=torch.Size([1000000, 15]), device=cpu, dtype=torch.float64, is_shared=True), qvel: MemoryMappedTensor(shape=torch.Size([1000000, 14]), device=cpu, dtype=torch.float64, is_shared=True), reward_ctrl: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), reward_forward: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), reward_survive: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), success: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.bool, is_shared=True), x_position: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), x_velocity: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), y_position: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), y_velocity: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True)}, batch_size=torch.Size([1000000]), device=cpu, is_shared=False), next: TensorDict( fields={ done: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.bool, is_shared=True), info: TensorDict( fields={ distance_from_origin: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), forward_reward: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), goal: MemoryMappedTensor(shape=torch.Size([1000000, 2]), device=cpu, dtype=torch.float64, is_shared=True), qpos: MemoryMappedTensor(shape=torch.Size([1000000, 15]), device=cpu, dtype=torch.float64, is_shared=True), qvel: MemoryMappedTensor(shape=torch.Size([1000000, 14]), device=cpu, dtype=torch.float64, is_shared=True), reward_ctrl: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), reward_forward: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), reward_survive: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), success: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.bool, is_shared=True), x_position: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), x_velocity: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), y_position: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), y_velocity: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True)}, batch_size=torch.Size([1000000]), device=cpu, is_shared=False), observation: TensorDict( fields={ achieved_goal: MemoryMappedTensor(shape=torch.Size([1000000, 2]), device=cpu, dtype=torch.float64, is_shared=True), desired_goal: MemoryMappedTensor(shape=torch.Size([1000000, 2]), device=cpu, dtype=torch.float64, is_shared=True), observation: MemoryMappedTensor(shape=torch.Size([1000000, 27]), device=cpu, dtype=torch.float64, is_shared=True)}, batch_size=torch.Size([1000000]), device=cpu, is_shared=False), reward: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.float64, is_shared=True), terminated: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.bool, is_shared=True), truncated: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.bool, is_shared=True)}, batch_size=torch.Size([1000000]), device=cpu, is_shared=False), observation: TensorDict( fields={ achieved_goal: MemoryMappedTensor(shape=torch.Size([1000000, 2]), device=cpu, dtype=torch.float64, is_shared=True), desired_goal: MemoryMappedTensor(shape=torch.Size([1000000, 2]), device=cpu, dtype=torch.float64, is_shared=True), observation: MemoryMappedTensor(shape=torch.Size([1000000, 27]), device=cpu, dtype=torch.float64, is_shared=True)}, batch_size=torch.Size([1000000]), device=cpu, is_shared=False)}, batch_size=torch.Size([1000000]), device=cpu, is_shared=False)), samplers=RandomSampler, writers=ImmutableDatasetWriter(), batch_size=32, transform=Compose( ), collate_fn=<function _collate_id at 0x120e21dc0>) >>> from torchrl.envs import CatTensors, Compose >>> from tempfile import TemporaryDirectory >>> >>> cat_tensors = CatTensors( ... in_keys=[("observation", "observation"), ("observation", "achieved_goal"), ... ("observation", "desired_goal")], ... out_key="obs" ... ) >>> cat_next_tensors = CatTensors( ... in_keys=[("next", "observation", "observation"), ... ("next", "observation", "achieved_goal"), ... ("next", "observation", "desired_goal")], ... out_key=("next", "obs") ... ) >>> t = Compose(cat_tensors, cat_next_tensors) >>> >>> def func(td): ... td = td.select( ... "action", ... "episode", ... ("next", "done"), ... ("next", "observation"), ... ("next", "reward"), ... ("next", "terminated"), ... ("next", "truncated"), ... "observation" ... ) ... td = t(td) ... return td >>> with TemporaryDirectory() as tmpdir: ... new_storage = data.preprocess(func, num_workers=4, pbar=True, mp_start_method="fork", dest=tmpdir) ... rb = ReplayBuffer(storage=new_storage) ... print(rb) ReplayBuffer( storage=TensorStorage( data=TensorDict( fields={ action: MemoryMappedTensor(shape=torch.Size([1000000, 8]), device=cpu, dtype=torch.float32, is_shared=True), episode: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.int64, is_shared=True), next: TensorDict( fields={ done: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.bool, is_shared=True), obs: MemoryMappedTensor(shape=torch.Size([1000000, 31]), device=cpu, dtype=torch.float64, is_shared=True), observation: TensorDict( fields={ }, batch_size=torch.Size([1000000]), device=cpu, is_shared=False), reward: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.float64, is_shared=True), terminated: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.bool, is_shared=True), truncated: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.bool, is_shared=True)}, batch_size=torch.Size([1000000]), device=cpu, is_shared=False), obs: MemoryMappedTensor(shape=torch.Size([1000000, 31]), device=cpu, dtype=torch.float64, is_shared=True), observation: TensorDict( fields={ }, batch_size=torch.Size([1000000]), device=cpu, is_shared=False)}, batch_size=torch.Size([1000000]), device=cpu, is_shared=False), shape=torch.Size([1000000]), len=1000000, max_size=1000000), sampler=RandomSampler(), writer=RoundRobinWriter(cursor=0, full_storage=True), batch_size=None, collate_fn=<function _collate_id at 0x168406fc0>)
- register_load_hook(hook: Callable[[Any], Any])¶
註冊儲存空間的載入 Hook。
注意
在儲存重播緩衝區時,目前不會序列化 Hook:每次建立緩衝區時,都必須手動重新初始化它們。
- register_save_hook(hook: Callable[[Any], Any])¶
註冊儲存空間的儲存 Hook。
注意
在儲存重播緩衝區時,目前不會序列化 Hook:每次建立緩衝區時,都必須手動重新初始化它們。
- sample(batch_size: Optional[int] = None, return_info: bool = False, include_info: Optional[bool] = None) TensorDictBase ¶
從 replay buffer 中取樣一批資料。
使用 Sampler 來取樣索引,並從 Storage 中檢索它們。
- 參數:
batch_size (int, optional) – 要收集的資料大小。如果沒有提供,此方法將按照 sampler 指示的大小取樣 batch。
return_info (bool) – 是否回傳 info。如果為 True,結果會是 tuple (資料, info)。如果為 False,結果是資料。
- 回傳:
一個 tensordict,其中包含 replay buffer 中選取的一批資料。如果 return_info 標記設定為 True,則為包含此 tensordict 和 info 的 tuple。
- set_storage(storage: Storage, collate_fn: Optional[Callable] = None)¶
在 replay buffer 中設定一個新的 storage 並回傳先前的 storage。
- 參數:
storage (Storage) – buffer 的新 storage。
collate_fn (callable, optional) – 如果有提供,collate_fn 會被設定為這個值。否則,它會重設為預設值。
- property write_count¶
透過 add 和 extend 在 buffer 中目前為止寫入的項目總數。