db.rs 4.6 KB
Newer Older
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
1
/// This code is massively inspired by Tokio mini-redis
2
3
4
use crate::infer::InferError;
use crate::infer::InferStreamResponse;
use crate::validation::ValidGenerateRequest;
5
use nohash_hasher::{BuildNoHashHasher, IntMap};
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
6
use parking_lot::Mutex;
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
7
8
use std::collections::BTreeMap;
use std::sync::Arc;
9
10
11
use text_generation_client::{Batch, Request};
use tokio::sync::mpsc::UnboundedSender;
use tokio::sync::OwnedSemaphorePermit;
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
12
use tokio::time::Instant;
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
13

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
14
/// Database entry
Olivier Dehaene's avatar
Olivier Dehaene committed
15
16
#[derive(Debug)]
pub(crate) struct Entry {
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
17
    /// Request
18
19
20
    pub request: ValidGenerateRequest,
    /// Response sender to communicate between the Infer struct and the batching_task
    pub response_tx: UnboundedSender<Result<InferStreamResponse, InferError>>,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
21
22
    /// Instant when this entry was created
    pub time: Instant,
23
24
    /// Instant when this entry was added to a batch
    pub batch_time: Option<Instant>,
25
26
    /// Permit
    pub _permit: OwnedSemaphorePermit,
Olivier Dehaene's avatar
Olivier Dehaene committed
27
28
}

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
29
/// Request Database
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
30
31
32
33
34
#[derive(Debug, Clone)]
pub(crate) struct Db {
    pub shared: Arc<Shared>,
}

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
35
/// Shared state
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
36
37
#[derive(Debug)]
pub struct Shared {
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
38
    state: Mutex<State>,
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
39
40
}

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
41
/// Database State
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
42
43
#[derive(Debug)]
struct State {
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
44
    /// Database entries organized in a BTreeMap to be able to iterate over them in order
Olivier Dehaene's avatar
Olivier Dehaene committed
45
    entries: BTreeMap<u64, Entry>,
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
46

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
47
    /// Id of the next entry
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
48
49
    next_id: u64,

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
50
    /// Id of the next batch
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
51
52
    next_batch_id: u64,

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
53
    /// Start ID of the next batch. Used to iterate inside the entries BTreeMap
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
54
55
56
    next_batch_start_id: u64,
}

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
57
58
impl State {
    /// Get the next requests
59
    fn next_requests(&self, max_size: usize) -> Option<(Vec<u64>, Vec<Request>)> {
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
60
61
62
63
64
65
66
67
68
69
70
71
72
73
        // Iterates for max_size over the BTreemap starting from next_batch_start_id
        let mut requests = Vec::new();
        let mut ids = Vec::new();

        for (id, entry) in self
            .entries
            // Start from next_batch_start_id
            .range(self.next_batch_start_id..)
            // Take max_size
            .take(max_size)
        {
            requests.push(Request {
                id: *id,
                inputs: entry.request.inputs.clone(),
74
75
76
                input_length: entry.request.input_length,
                parameters: Some(entry.request.parameters.clone()),
                stopping_parameters: Some(entry.request.stopping_parameters.clone()),
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
77
78
79
80
81
82
83
84
85
86
87
88
89
            });

            ids.push(*id);
        }

        if requests.is_empty() {
            None
        } else {
            Some((ids, requests))
        }
    }
}

Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
90
91
impl Db {
    pub(crate) fn new() -> Self {
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
92
        // Shared state
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
93
        let shared = Arc::new(Shared {
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
94
            state: Mutex::new(State {
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
95
96
97
98
99
100
101
102
103
104
                entries: BTreeMap::new(),
                next_id: 0,
                next_batch_id: 0,
                next_batch_start_id: 0,
            }),
        });

        Self { shared }
    }

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
105
    /// Append an entry to the database
Olivier Dehaene's avatar
Olivier Dehaene committed
106
    pub(crate) fn append(&self, entry: Entry) {
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
107
108
        // Acquire lock
        let mut state = self.shared.state.lock();
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
109

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
110
        // Insert entry
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
111
112
        let id = state.next_id;
        state.next_id += 1;
Olivier Dehaene's avatar
Olivier Dehaene committed
113
        state.entries.insert(id, entry);
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
114
115
    }

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
116
117
118
119
120
    // Get the next batch
    pub(crate) fn next_batch(
        &self,
        min_size: Option<usize>,
        max_size: usize,
121
    ) -> Option<(IntMap<u64, Entry>, Batch)> {
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
122
123
124
125
        // Acquire lock
        let mut state = self.shared.state.lock();

        // Get requests from the database
126
        if let Some((ids, requests)) = state.next_requests(max_size) {
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
127
128
129
130
131
132
            if let Some(min_size) = min_size {
                // If min_size is set, only return a batch if there are enough requests
                if requests.len() < min_size {
                    return None;
                }
            }
133
134
135
136
            // Batch size
            let size = requests.len();

            let mut entries = IntMap::with_capacity_and_hasher(size, BuildNoHashHasher::default());
137
            ids.iter().for_each(|id| {
138
139
140
141
142
143
                // Remove entry from db
                let mut entry = state.entries.remove(id).unwrap();
                // Set batch_time
                entry.batch_time = Some(Instant::now());
                // Insert in entries IntMap
                entries.insert(*id, entry);
144
            });
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
145
146
147
148

            let batch = Batch {
                id: state.next_batch_id,
                requests,
Olivier Dehaene's avatar
Olivier Dehaene committed
149
                size: size as u32,
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
150
            };
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
151
152
153
            // Update next_batch_start_id to the last id in the batch + 1
            state.next_batch_start_id = ids.last().unwrap() + 1;
            // Increment batch id
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
154
            state.next_batch_id += 1;
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
155

156
            return Some((entries, batch));
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
157
158
159
        }
        None
    }
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
160
}