detached_replay_buffer.py 2.47 KB
Newer Older
1
from typing import List
2
3

import torch
4
from coati.experience_buffer.utils import BufferItem, make_experience_batch, split_experience_batch
5
from coati.experience_maker.base import Experience
6

7
8
9
# from torch.multiprocessing import Queue
from ray.util.queue import Queue

10
11

class DetachedReplayBuffer:
12
    """
13
        Detached replay buffer. Share Experience across workers on the same node.
14
        Therefore, a trainer node is expected to have only one instance.
15
        It is ExperienceMakerHolder's duty to call append(exp) method, remotely.
16

17
18
19
20
21
    Args:
        sample_batch_size: Batch size when sampling. Exp won't enqueue until they formed a batch.
        tp_world_size: Number of workers in the same tp group
        limit: Limit of number of experience sample BATCHs. A number <= 0 means unlimited. Defaults to 0.
        cpu_offload: Whether to offload experience to cpu when sampling. Defaults to True.
22
    """
23

24
    def __init__(self, sample_batch_size: int, limit: int = 0) -> None:
25
26
        self.sample_batch_size = sample_batch_size
        self.limit = limit
27
28
        self.items = Queue(self.limit, actor_options={"num_cpus": 1})
        self.batch_collector: List[BufferItem] = []
29

30
31
    @torch.no_grad()
    def append(self, experience: Experience) -> None:
32
        """
33
        Expected to be called remotely.
34
        """
35
36
        items = split_experience_batch(experience)
        self.extend(items)
37
38

    @torch.no_grad()
39
    def extend(self, items: List[BufferItem]) -> None:
40
        """
41
        Expected to be called remotely.
42
        """
43
44
        self.batch_collector.extend(items)
        while len(self.batch_collector) >= self.sample_batch_size:
45
            items = self.batch_collector[: self.sample_batch_size]
46
47
            experience = make_experience_batch(items)
            self.items.put(experience, block=True)
48
            self.batch_collector = self.batch_collector[self.sample_batch_size :]
49
50
51
52
53
54
55

    def clear(self) -> None:
        # self.items.close()
        self.items.shutdown()
        self.items = Queue(self.limit)
        self.worker_state = [False] * self.tp_world_size
        self.batch_collector = []
56

57
    @torch.no_grad()
58
59
    def sample(self, worker_rank=0, to_device="cpu") -> Experience:
        ret = self._sample_and_erase()
60
61
62
63
64
65
66
67
68
69
        ret.to_device(to_device)
        return ret

    @torch.no_grad()
    def _sample_and_erase(self) -> Experience:
        ret = self.items.get(block=True)
        return ret

    def get_length(self) -> int:
        ret = self.items.qsize()
70
        return ret