Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] Max Value Writer #1622

Merged
merged 22 commits into from
Oct 18, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion torchrl/data/replay_buffers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,9 @@
Storage,
TensorStorage,
)
from .writers import RoundRobinWriter, TensorDictRoundRobinWriter, Writer
from .writers import (
RoundRobinWriter,
TensorDictMaxValueWriter,
TensorDictRoundRobinWriter,
Writer,
)
66 changes: 66 additions & 0 deletions torchrl/data/replay_buffers/writers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

import heapq
from abc import ABC, abstractmethod
from typing import Any, Dict, Sequence

Expand Down Expand Up @@ -92,3 +93,68 @@ def extend(self, data: Sequence) -> torch.Tensor:
data["index"] = index
self._storage[index] = data
return index


class TensorDictMaxValueWriter(Writer):
"""A Writer class for composable replay buffers that keeps the top elements based on some ranking key.

If rank_key is not provided, the key will be ("next", "reward").
albertbou92 marked this conversation as resolved.
Show resolved Hide resolved
"""
albertbou92 marked this conversation as resolved.
Show resolved Hide resolved

def __init__(self, rank_key=None, **kw) -> None:
super().__init__(**kw)
albertbou92 marked this conversation as resolved.
Show resolved Hide resolved
self._cursor = 0
self._current_top_values = []
self._rank_key = rank_key
if self._rank_key is None:
self._rank_key = ("next", "reward")

def add(self, data: Any) -> int:

ret = None

# Sum the rank key, in case it is a whole trajectory
rank_data = data.get("_data")[self._rank_key].sum()
albertbou92 marked this conversation as resolved.
Show resolved Hide resolved

if rank_data is None:
raise ValueError(f"Rank key {self._rank_key} not found in data.")
albertbou92 marked this conversation as resolved.
Show resolved Hide resolved

# If the buffer is not full, add the data
if len(self._storage) < self._storage.max_size:

ret = self._cursor
data["index"] = ret
albertbou92 marked this conversation as resolved.
Show resolved Hide resolved
self._storage[self._cursor] = data
self._cursor = (self._cursor + 1) % self._storage.max_size

# Add new reward to the heap
heapq.heappush(self._current_top_values, (rank_data, ret))

# If the buffer is full, check if the new data is better than the worst data in the buffer
elif rank_data > self._current_top_values[0][0]:

# retrieve position of the smallest value
min_sample = heapq.heappop(self._current_top_values)
min_sample_value = min_sample[1]

# replace the smallest value with the new value
self._storage[min_sample_value] = data

# set new data index
data["index"] = min_sample_value
albertbou92 marked this conversation as resolved.
Show resolved Hide resolved

# set return value
ret = min_sample_value

# Add new reward to the heap
heapq.heappush(self._current_top_values, (rank_data, ret))

return ret

def extend(self, data: Sequence) -> None:
for sample in data:
self.add(sample)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this efficient when data is a TensorDict?
Shouldn't we batch these ops?

Copy link
Contributor Author

@albertbou92 albertbou92 Oct 11, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How? if we need to check whether or not the values are higher that the current stored values we need to check them one by one.

maybe we can pre-sort the td values or something and try to make it a bit more efficient


def _empty(self) -> None:
self._cursor = 0
self._current_top_values = []