cache.py 645 Bytes
Newer Older
1
from typing import Dict, Optional, TypeVar
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
2

3
from text_generation_server.models.types import Batch
4

5
6
B = TypeVar("B", bound=Batch)

Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
7
8
9

class Cache:
    def __init__(self):
10
        self.cache: Dict[int, B] = {}
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
11

12
    def pop(self, batch_id: int) -> Optional[B]:
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
13
14
        return self.cache.pop(batch_id, None)

15
    def set(self, entry: B):
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
16
17
18
        if entry is not None:
            self.cache[entry.batch_id] = entry

Olivier Dehaene's avatar
Olivier Dehaene committed
19
    def delete(self, batch_id: int):
20
21
22
        batch = self.pop(batch_id)
        if batch is not None:
            del batch
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
23
24
25
26
27
28

    def clear(self):
        self.cache.clear()

    def __len__(self):
        return len(self.cache.keys())