|
| 1 | +import time |
| 2 | +from typing import List, Optional |
| 3 | + |
| 4 | +import ray |
| 5 | +from sqlalchemy import asc, create_engine, desc |
| 6 | +from sqlalchemy.exc import OperationalError |
| 7 | +from sqlalchemy.orm import sessionmaker |
| 8 | +from sqlalchemy.pool import NullPool |
| 9 | + |
| 10 | +from trinity.buffer.schema import Base, create_dynamic_table |
| 11 | +from trinity.buffer.utils import retry_session |
| 12 | +from trinity.common.config import BufferConfig, StorageConfig |
| 13 | +from trinity.common.constants import ReadStrategy |
| 14 | +from trinity.utils.log import get_logger |
| 15 | + |
| 16 | + |
| 17 | +class DBWrapper: |
| 18 | + """ |
| 19 | + A wrapper of a SQL database. |
| 20 | +
|
| 21 | + If `wrap_in_ray` in `StorageConfig` is `True`, this class will be run as a Ray Actor, |
| 22 | + and provide a remote interface to the local database. |
| 23 | +
|
| 24 | + For databases that do not support multi-processing read/write (e.g. sqlite, duckdb), we |
| 25 | + recommend setting `wrap_in_ray` to `True` |
| 26 | + """ |
| 27 | + |
| 28 | + def __init__(self, storage_config: StorageConfig, config: BufferConfig) -> None: |
| 29 | + self.logger = get_logger(__name__) |
| 30 | + self.engine = create_engine(storage_config.path, poolclass=NullPool) |
| 31 | + self.table_model_cls = create_dynamic_table( |
| 32 | + storage_config.algorithm_type, storage_config.name |
| 33 | + ) |
| 34 | + |
| 35 | + try: |
| 36 | + Base.metadata.create_all(self.engine, checkfirst=True) |
| 37 | + except OperationalError: |
| 38 | + self.logger.warning("Failed to create database, assuming it already exists.") |
| 39 | + |
| 40 | + self.session = sessionmaker(bind=self.engine) |
| 41 | + self.batch_size = config.read_batch_size |
| 42 | + self.max_retry_times = config.max_retry_times |
| 43 | + self.max_retry_interval = config.max_retry_interval |
| 44 | + |
| 45 | + @classmethod |
| 46 | + def get_wrapper(cls, storage_config: StorageConfig, config: BufferConfig): |
| 47 | + if storage_config.wrap_in_ray: |
| 48 | + return ( |
| 49 | + ray.remote(cls) |
| 50 | + .options( |
| 51 | + name=f"sql-{storage_config.name}", |
| 52 | + get_if_exists=True, |
| 53 | + ) |
| 54 | + .remote(storage_config, config) |
| 55 | + ) |
| 56 | + else: |
| 57 | + return cls(storage_config, config) |
| 58 | + |
| 59 | + def write(self, data: list) -> None: |
| 60 | + with retry_session(self.session, self.max_retry_times, self.max_retry_interval) as session: |
| 61 | + experience_models = [self.table_model_cls.from_experience(exp) for exp in data] |
| 62 | + session.add_all(experience_models) |
| 63 | + |
| 64 | + def read(self, strategy: Optional[ReadStrategy] = None) -> List: |
| 65 | + if strategy is None: |
| 66 | + strategy = ReadStrategy.LFU |
| 67 | + |
| 68 | + if strategy == ReadStrategy.LFU: |
| 69 | + sortOrder = (asc(self.table_model_cls.consumed), desc(self.table_model_cls.id)) |
| 70 | + |
| 71 | + elif strategy == ReadStrategy.LRU: |
| 72 | + sortOrder = (desc(self.table_model_cls.id),) |
| 73 | + |
| 74 | + elif strategy == ReadStrategy.PRIORITY: |
| 75 | + sortOrder = (desc(self.table_model_cls.priority), desc(self.table_model_cls.id)) |
| 76 | + |
| 77 | + else: |
| 78 | + raise NotImplementedError(f"Unsupported strategy {strategy} by SQLStorage") |
| 79 | + |
| 80 | + exp_list = [] |
| 81 | + while len(exp_list) < self.batch_size: |
| 82 | + if len(exp_list): |
| 83 | + self.logger.info("waiting for experiences...") |
| 84 | + time.sleep(1) |
| 85 | + with retry_session( |
| 86 | + self.session, self.max_retry_times, self.max_retry_interval |
| 87 | + ) as session: |
| 88 | + # get a batch of experiences from the database |
| 89 | + experiences = ( |
| 90 | + session.query(self.table_model_cls) |
| 91 | + .filter(self.table_model_cls.reward.isnot(None)) |
| 92 | + .order_by(*sortOrder) # TODO: very slow |
| 93 | + .limit(self.batch_size - len(exp_list)) |
| 94 | + .with_for_update() |
| 95 | + .all() |
| 96 | + ) |
| 97 | + # update the consumed field |
| 98 | + for exp in experiences: |
| 99 | + exp.consumed += 1 |
| 100 | + exp_list.extend([self.table_model_cls.to_experience(exp) for exp in experiences]) |
| 101 | + self.logger.info(f"get {len(exp_list)} experiences:") |
| 102 | + self.logger.info(f"reward = {[exp.reward for exp in exp_list]}") |
| 103 | + self.logger.info(f"first prompt_text = {exp_list[0].prompt_text}") |
| 104 | + self.logger.info(f"first response_text = {exp_list[0].response_text}") |
| 105 | + return exp_list |
0 commit comments