db.rs 5.33 KB
Newer Older
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
1
/// This code is massively inspired by Tokio mini-redis
2
3
use crate::infer::InferError;
use crate::infer::InferStreamResponse;
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
4
use crate::{GenerateParameters, GenerateRequest};
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
use text_generation_client::{
10
    Batch, NextTokenChooserParameters, Request, StoppingCriteriaParameters,
11
};
12
13
use tokio::sync::mpsc::UnboundedSender;
use tokio::sync::OwnedSemaphorePermit;
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
14
use tokio::time::Instant;
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
15

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
16
/// Database entry
Olivier Dehaene's avatar
Olivier Dehaene committed
17
18
#[derive(Debug)]
pub(crate) struct Entry {
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
19
    /// Request
Olivier Dehaene's avatar
Olivier Dehaene committed
20
    pub request: GenerateRequest,
21
22
    /// 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
23
    /// Number of tokens in the input
Olivier Dehaene's avatar
Olivier Dehaene committed
24
    pub input_length: usize,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
25
26
    /// Instant when this entry was created
    pub time: Instant,
27
28
    /// Instant when this entry was added to a batch
    pub batch_time: Option<Instant>,
29
30
    /// Permit
    pub _permit: OwnedSemaphorePermit,
Olivier Dehaene's avatar
Olivier Dehaene committed
31
32
}

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

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

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

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
51
    /// Id of the next entry
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
52
53
    next_id: u64,

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
54
    /// Id of the next batch
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
55
56
    next_batch_id: u64,

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
57
    /// Start ID of the next batch. Used to iterate inside the entries BTreeMap
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
58
59
60
    next_batch_start_id: u64,
}

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
61
62
impl State {
    /// Get the next requests
63
    fn next_requests(&self, max_size: usize) -> Option<(Vec<u64>, Vec<Request>)> {
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
        // 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(),
                input_length: entry.input_length as u32,
79
80
                parameters: Some((&entry.request.parameters).into()),
                stopping_parameters: Some(entry.request.parameters.clone().into()),
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
81
82
83
84
85
86
87
88
89
90
91
92
93
            });

            ids.push(*id);
        }

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

Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
94
95
impl Db {
    pub(crate) fn new() -> Self {
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
96
        // Shared state
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
97
        let shared = Arc::new(Shared {
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
98
            state: Mutex::new(State {
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
99
100
101
102
103
104
105
106
107
108
                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
109
    /// Append an entry to the database
Olivier Dehaene's avatar
Olivier Dehaene committed
110
    pub(crate) fn append(&self, entry: Entry) {
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
111
112
        // Acquire lock
        let mut state = self.shared.state.lock();
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
113

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
114
        // Insert entry
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
115
116
        let id = state.next_id;
        state.next_id += 1;
Olivier Dehaene's avatar
Olivier Dehaene committed
117
        state.entries.insert(id, entry);
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
118
119
    }

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

        // Get requests from the database
130
        if let Some((ids, requests)) = state.next_requests(max_size) {
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
131
132
133
134
135
136
            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;
                }
            }
137
138
139
140
            // Batch size
            let size = requests.len();

            let mut entries = IntMap::with_capacity_and_hasher(size, BuildNoHashHasher::default());
141
            ids.iter().for_each(|id| {
142
143
144
145
146
147
                // 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);
148
            });
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
149
150
151
152

            let batch = Batch {
                id: state.next_batch_id,
                requests,
Olivier Dehaene's avatar
Olivier Dehaene committed
153
                size: size as u32,
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
154
            };
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
155
156
157
            // 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
158
            state.next_batch_id += 1;
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
159

160
            return Some((entries, batch));
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
161
162
163
        }
        None
    }
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
164
}
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
165

166
167
impl From<&GenerateParameters> for NextTokenChooserParameters {
    fn from(parameters: &GenerateParameters) -> Self {
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
168
169
170
171
172
        Self {
            temperature: parameters.temperature,
            top_k: parameters.top_k as u32,
            top_p: parameters.top_p,
            do_sample: parameters.do_sample,
173
            seed: parameters.seed,
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
174
175
176
        }
    }
}
177
178
179
180
181
182
183
184
185

impl From<GenerateParameters> for StoppingCriteriaParameters {
    fn from(parameters: GenerateParameters) -> Self {
        Self {
            stop_sequences: parameters.stop,
            max_new_tokens: parameters.max_new_tokens,
        }
    }
}