TensorDictPrioritizedReplayBuffer¶
- class torchrl.data.TensorDictPrioritizedReplayBuffer(*, alpha: float, beta: float, priority_key: str = 'td_error', eps: float = 1e-08, storage: Storage | None = None, collate_fn: Callable | None = None, pin_memory: bool = False, prefetch: int | None = None, transform: 'Transform' | None = None, reduction: str = 'max', batch_size: int | None = None, dim_extend: int | None = None, generator: torch.Generator | None = None, shared: bool = False)[source]¶
圍繞
PrioritizedReplayBuffer
類別的 TensorDict 特定包裝器。這個類別會傳回帶有新鍵
"index"
的 tensordict,這個鍵代表重播緩衝區中每個元素的索引。它也提供update_tensordict_priority()
方法,這個方法只需要將 tensordict 傳遞給它,並帶有新的優先順序值。- 關鍵字引數:
alpha (float) – 指數 α 決定使用了多少優先順序,其中 α = 0 對應於統一的情況。
beta (float) – 重要性抽樣負指數。
eps (float) – 加入至優先順序的 delta,以確保緩衝區不包含空優先順序。
storage (Storage, optional) – 要使用的儲存體。如果沒有提供,將會建立預設的
ListStorage
,其max_size
為1_000
。collate_fn (callable, optional) – 合併樣本清單以形成 Tensor(s)/輸出的迷你批次。在從地圖樣式的資料集中使用批次載入時使用。預設值將根據儲存體類型決定。
pin_memory (bool) – 是否應該在 rb 樣本上呼叫 pin_memory()。
prefetch (int, optional) – 要使用多執行緒預先擷取的下一個批次數。預設為 None(無預先擷取)。
transform (Transform, optional) – 在呼叫 sample() 時要執行的轉換。若要串聯轉換,請使用
Compose
類別。轉換應該與tensordict.TensorDict
內容搭配使用。如果與其他結構搭配使用,則轉換應該使用"data"
前導鍵進行編碼,該金鑰將用於從非 tensordict 內容建構 tensordict。batch_size (int, optional) –
呼叫 sample() 時要使用的批次大小。 .. note
The batch-size can be specified at construction time via the ``batch_size`` argument, or at sampling time. The former should be preferred whenever the batch-size is consistent across the experiment. If the batch-size is likely to change, it can be passed to the :meth:`~.sample` method. This option is incompatible with prefetching (since this requires to know the batch-size in advance) as well as with samplers that have a ``drop_last`` argument.
priority_key (str, optional) – 假設優先順序儲存在新增至此 ReplayBuffer 的 TensorDict 中的索引鍵。這將在取樣器類型為
PrioritizedSampler
時使用。預設為"td_error"
。reduction (str, optional) – 多維 tensordict(即儲存的軌跡)的縮減方法。可以是 “max”、“min”、“median” 或 “mean” 之一。
dim_extend (int, optional) –
表示在呼叫
extend()
時,要考慮擴展的維度。預設值為storage.ndim-1
。當使用dim_extend > 0
時,如果該引數可用,我們建議在儲存體實例化中使用ndim
引數,以便讓儲存體知道資料是多維的,並在取樣期間保持儲存容量和批次大小的一致性。generator (torch.Generator, optional) –
用於取樣的生成器。為重播緩衝區使用專用生成器可以對種子進行細粒度控制,例如保持全域種子不同,但對於分散式作業,RB 種子相同。預設值為
None
(全域預設生成器)。警告
截至目前,生成器對轉換沒有影響。
shared (bool, optional) – 緩衝區是否將使用多處理共享。預設值為
False
。
範例
>>> import torch >>> >>> from torchrl.data import LazyTensorStorage, TensorDictPrioritizedReplayBuffer >>> from tensordict import TensorDict >>> >>> torch.manual_seed(0) >>> >>> rb = TensorDictPrioritizedReplayBuffer(alpha=0.7, beta=1.1, storage=LazyTensorStorage(10), batch_size=5) >>> data = TensorDict({"a": torch.ones(10, 3), ("b", "c"): torch.zeros(10, 3, 1)}, [10]) >>> rb.extend(data) >>> print("len of rb", len(rb)) len of rb 10 >>> sample = rb.sample(5) >>> print(sample) TensorDict( fields={ _weight: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.float32, is_shared=False), a: Tensor(shape=torch.Size([5, 3]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([5, 3, 1]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([5]), device=cpu, is_shared=False), index: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.int64, is_shared=False)}, batch_size=torch.Size([5]), device=cpu, is_shared=False) >>> print("index", sample["index"]) index tensor([9, 5, 2, 2, 7]) >>> # give a high priority to these samples... >>> sample.set("td_error", 100*torch.ones(sample.shape)) >>> # and update priority >>> rb.update_tensordict_priority(sample) >>> # the new sample should have a high overlap with the previous one >>> sample = rb.sample(5) >>> print(sample) TensorDict( fields={ _weight: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.float32, is_shared=False), a: Tensor(shape=torch.Size([5, 3]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([5, 3, 1]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([5]), device=cpu, is_shared=False), index: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.int64, is_shared=False)}, batch_size=torch.Size([5]), device=cpu, is_shared=False) >>> print("index", sample["index"]) index tensor([2, 5, 5, 9, 7])
- add(data: TensorDictBase) int ¶
向重播緩衝區添加單個元素。
- 參數:
data (Any) – 要添加到重播緩衝區的資料
- 返回:
資料在重播緩衝區中的索引。
- append_transform(transform: Transform, *, invert: bool = False) ReplayBuffer ¶
在末尾附加轉換。
當呼叫 sample 時,轉換會依序套用。
- 參數:
transform (Transform) – 要附加的轉換
- 關鍵字引數:
invert (bool, optional) – 如果
True
,則轉換將被反轉(正向呼叫將在寫入期間呼叫,而反向呼叫將在讀取期間呼叫)。預設值為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()
- 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) – 要添加到重播緩衝區的資料集合。
- 返回:
添加到重播緩衝區的資料索引。
警告
當處理值列表時,
extend()
可能具有不明確的簽名,該簽名應被解釋為 PyTree(在這種情況下,列表中的所有元素都將被放入儲存體中儲存的 PyTree 中的切片中)或要一次添加一個的值列表。為了解決這個問題,TorchRL 明確區分了 list 和 tuple:tuple 將被視為 PyTree,list(在根層級)將被解釋為要一次一個添加到緩衝區的值堆疊。對於ListStorage
實例,只能提供未綁定的元素(沒有 PyTree)。
- insert_transform(index: int, transform: Transform, *, invert: bool = False) ReplayBuffer ¶
插入 transform。
當呼叫 sample 時,Transforms 會依序執行。
- 參數:
index (int) – 插入 transform 的位置。
transform (Transform) – 要附加的轉換
- 關鍵字引數:
invert (bool, optional) – 如果
True
,則轉換將被反轉(正向呼叫將在寫入期間呼叫,而反向呼叫將在讀取期間呼叫)。預設值為False
。
- loads(path)¶
載入給定路徑的回放緩衝區狀態。
緩衝區應具有匹配的元件,並使用
dumps()
儲存。- 參數:
path (Path 或 str) – 回放緩衝區儲存的路徑。
更多資訊請參考
dumps()
。
- register_load_hook(hook: Callable[[Any], Any])¶
為儲存註冊載入 hook。
注意
儲存回放緩衝區時,目前不會序列化 Hooks:每次建立緩衝區時都必須手動重新初始化。
- register_save_hook(hook: Callable[[Any], Any])¶
為儲存註冊儲存 hook。
注意
儲存回放緩衝區時,目前不會序列化 Hooks:每次建立緩衝區時都必須手動重新初始化。
- sample(batch_size: Optional[int] = None, return_info: bool = False, include_info: Optional[bool] = None) TensorDictBase ¶
從回放緩衝區取樣一批資料。
使用 Sampler 取樣索引,並從 Storage 檢索它們。
- 參數:
batch_size (int, optional) – 要收集的資料大小。如果未提供,此方法將按照 sampler 指示的方式取樣 batch-size。
return_info (bool) – 是否返回 info。 如果為 True,則結果為元組 (data, info)。 如果為 False,則結果為資料。
- 返回:
包含在回放緩衝區中選取的一批資料的 tensordict。 如果 return_info 標誌設定為 True,則包含此 tensordict 和 info 的元組。
- set_storage(storage: Storage, collate_fn: Optional[Callable] = None)¶
在回放緩衝區中設定新的 storage,並返回先前的 storage。
- 參數:
storage (Storage) – 緩衝區的新儲存空間。
collate_fn (callable, optional) – 如果提供,則 collate_fn 會設定為這個值。否則,它會重置為預設值。
- property write_count¶
目前透過 add 和 extend 寫入緩衝區的項目總數。