Skip to content

Commit 42065ab

Browse files
committed
perf(embeddings): rotate sessions via round-robin
1 parent caedb5c commit 42065ab

1 file changed

Lines changed: 14 additions & 3 deletions

File tree

embeddings/src/model/local.rs

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -780,6 +780,7 @@ pub struct OnnxEmbeddingModel {
780780
tokenizer: Tokenizer,
781781
max_input_len: usize,
782782
hidden_size: usize,
783+
next_session: std::sync::atomic::AtomicUsize,
783784
}
784785

785786
impl OnnxEmbeddingModel {
@@ -831,9 +832,17 @@ impl OnnxEmbeddingModel {
831832
tokenizer,
832833
max_input_len,
833834
hidden_size,
835+
next_session: std::sync::atomic::AtomicUsize::new(0),
834836
})
835837
}
836838

839+
/// Pick next session round-robin for concurrent callers.
840+
fn next_session_idx(&self) -> usize {
841+
self.next_session
842+
.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
843+
% self.sessions.len()
844+
}
845+
837846
/// Run a single ONNX forward pass on one batch.
838847
fn run_batch(
839848
session: &mut ort::session::Session,
@@ -984,11 +993,12 @@ impl OnnxEmbeddingModel {
984993

985994
let text_batches: Vec<&[&str]> = texts.chunks(bs).collect();
986995

987-
// Single batch — no pipeline overhead needed
996+
// Single batch — pick session round-robin for concurrent callers
988997
if text_batches.len() == 1 {
998+
let idx = self.next_session_idx();
989999
let chunks = Self::tokenize_batch(tokenizer, text_batches[0], max_input)
9901000
.map_err(|e| -> Box<dyn Error> { Box::new(e) })?;
991-
return Self::run_batch(&mut self.sessions[0].lock().unwrap(), &chunks);
1001+
return Self::run_batch(&mut self.sessions[idx].lock().unwrap(), &chunks);
9921002
}
9931003

9941004
// Pipeline: tokenizer thread feeds batches, main thread runs inference
@@ -1010,7 +1020,8 @@ impl OnnxEmbeddingModel {
10101020
}
10111021
});
10121022

1013-
let mut session = self.sessions[0].lock().unwrap();
1023+
let idx = self.next_session_idx();
1024+
let mut session = self.sessions[idx].lock().unwrap();
10141025
for chunks in rx {
10151026
match Self::run_batch(&mut session, &chunks) {
10161027
Ok(embs) => all_embeddings.extend(embs),

0 commit comments

Comments
 (0)