PrioritizedReplayBuffer¶
- class torchrl.data.PrioritizedReplayBuffer(*, alpha: float, beta: float, eps: float = 1e-08, dtype: torch.dtype = torch.float32, storage: Storage | None = None, collate_fn: Callable | None = None, pin_memory: bool = False, prefetch: int | None = None, transform: 'Transform' | None = None, batch_size: int | None = None, dim_extend: int | None = None)[source]¶
優先排序重播緩衝區。
所有引數都必須使用關鍵字引數。
- 呈現於
“Schaul, T.; Quan, J.; Antonoglou, I.; and Silver, D. 2015. Prioritized experience replay.” (https://arxiv.org/abs/1511.05952)
- 參數:
alpha (float) – 指數 α 決定了優先排序的使用程度,α = 0 對應於統一的情況。
beta (float) – 重要性取樣負指數。
eps (float) – 添加到優先級的增量,以確保緩衝區不包含空優先級。
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() 時要執行的 Transform。 若要鏈式轉換,請使用
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.
dim_extend (int, optional) –
指示在呼叫
extend()
時要考慮用於擴展的 dim。 預設值為storage.ndim-1
。 當使用dim_extend > 0
時,如果該引數可用,我們建議在儲存體例項化中使用ndim
引數,讓儲存體知道資料是多維的,並在取樣期間保持儲存容量和批次大小的一致概念。
Note
通用的優先排序重播緩衝區(例如,非 tensordict 後端的)需要呼叫
sample()
,並將return_info
參數設為True
,才能存取索引,進而更新優先順序。 使用tensordict.TensorDict
和相關的TensorDictPrioritizedReplayBuffer
可以簡化此流程。範例
>>> import torch >>> >>> from torchrl.data import ListStorage, PrioritizedReplayBuffer >>> >>> torch.manual_seed(0) >>> >>> rb = PrioritizedReplayBuffer(alpha=0.7, beta=0.9, storage=ListStorage(10)) >>> data = range(10) >>> rb.extend(data) >>> sample = rb.sample(3) >>> print(sample) tensor([1, 0, 1]) >>> # get the info to find what the indices are >>> sample, info = rb.sample(5, return_info=True) >>> print(sample, info) tensor([2, 7, 4, 3, 5]) {'_weight': array([1., 1., 1., 1., 1.], dtype=float32), 'index': array([2, 7, 4, 3, 5])} >>> # update priority >>> priority = torch.ones(5) * 5 >>> rb.update_priority(info["index"], priority) >>> # and now a new sample, the weights should be updated >>> sample, info = rb.sample(5, return_info=True) >>> print(sample, info) tensor([2, 5, 2, 2, 5]) {'_weight': array([0.36278465, 0.36278465, 0.36278465, 0.36278465, 0.36278465], dtype=float32), 'index': array([2, 5, 2, 2, 5])}
- add(data: Any) 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 或 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(data: Sequence) Tensor ¶
使用可迭代物件中包含的一個或多個元素來擴充重播緩衝區。
如果存在,將呼叫反向轉換。`
- 參數:
data (iterable) – 要添加到重播緩衝區的資料集合。
- 回傳:
添加到重播緩衝區的資料的索引。
警告
當處理值列表時,
extend()
可能具有不明確的簽章,這些值列表應被解釋為 PyTree(在這種情況下,列表中的所有元素都將放置在儲存的 PyTree 中的一個切片中)或要一次添加一個的值列表。 為了解決這個問題,TorchRL 對列表和元組進行了明確的區分:元組將被視為 PyTree,列表(在根層級)將被解釋為要一次一個地添加到緩衝區的值堆疊。 對於ListStorage
實例,只能提供未綁定的元素(沒有 PyTrees)。
- insert_transform(index: int, transform: Transform, *, invert: bool = False) ReplayBuffer ¶
插入轉換。
當呼叫 sample 時,轉換會依序執行。
- 參數:
index (int) – 插入轉換的位置。
transform (Transform) – 要附加的轉換
- 關鍵字引數:
invert (bool, optional) – 如果
True
,則轉換將被反轉(正向呼叫將在寫入期間呼叫,反向呼叫將在讀取期間呼叫)。預設值為False
。
- loads(path)¶
在給定路徑載入重播緩衝區狀態。
緩衝區應具有相符的組件,並使用
dumps()
儲存。- 參數:
path (Path 或 str) – 重播緩衝區儲存的路徑。
請參閱
dumps()
以取得更多資訊。
- register_load_hook(hook: Callable[[Any], Any])¶
為儲存空間註冊一個載入鉤子 (load hook)。
Note
目前在儲存回放緩衝區 (replay buffer) 時,鉤子不會被序列化:每次建立緩衝區時都必須手動重新初始化它們。
- register_save_hook(hook: Callable[[Any], Any])¶
為儲存空間註冊一個儲存鉤子 (save hook)。
Note
目前在儲存回放緩衝區 (replay buffer) 時,鉤子不會被序列化:每次建立緩衝區時都必須手動重新初始化它們。
- sample(batch_size: Optional[int] = None, return_info: bool = False) Any ¶
從回放緩衝區中抽樣一批資料。
使用 Sampler 抽樣索引,並從 Storage 檢索它們。
- 參數:
batch_size (int, optional) – 要收集的資料大小。 如果未提供,此方法將按照 sampler 指示的方式抽樣一個 batch-size。
return_info (bool) – 是否回傳 info。 如果為 True,結果將是一個 tuple (data, info)。 如果為 False,結果將是 data。
- 回傳:
在回放緩衝區中選取的一批資料。如果 return_info 標誌設定為 True,則為包含此批次和 info 的 tuple。
- set_storage(storage: Storage, collate_fn: Optional[Callable] = None)¶
在回放緩衝區中設定一個新的 storage,並回傳之前的 storage。
- 參數:
storage (Storage) – 緩衝區的新 storage。
collate_fn (callable, optional) – 如果提供,collate_fn 會設定為這個值。 否則,它將重設為預設值。
- property write_count¶
透過 add 和 extend 在緩衝區中寫入的項目總數。