web search done right
incorporate term distance into ranking
Mikkel Denker9ee9c6338ef8
diff --git a/crates/core/src/ranking/bm25.rs b/crates/core/src/ranking/bm25.rsindex 853b4329..7530131f 100644--- a/crates/core/src/ranking/bm25.rs+++ b/crates/core/src/ranking/bm25.rs@@ -139,6 +139,10 @@ impl Bm25Weight {#[inline]pub fn tf_factor(&self, fieldnorm_id: u8, term_freq: u32) -> Score {+ if term_freq == 0 {+ return 0.0;+ }+let term_freq = term_freq as Score;let norm = self.cache[fieldnorm_id as usize];(term_freq * (self.constants.k1 + 1.0)) / (term_freq + norm)diff --git a/crates/core/src/ranking/bm25f.rs b/crates/core/src/ranking/bm25f.rsindex ba5b549b..f1b0cad5 100644--- a/crates/core/src/ranking/bm25f.rs+++ b/crates/core/src/ranking/bm25f.rs@@ -135,6 +135,10 @@ impl Bm25FWeight {#[inline]pub fn tf_factor(&self, coefficient: Score, fieldnorm_id: u8, term_freq: u32) -> Score {+ if term_freq == 0 {+ return 0.0;+ }+let term_freq = term_freq as Score * coefficient;let norm = self.cache[fieldnorm_id as usize];(term_freq * (self.constants.k1 + 1.0)) / (term_freq + norm)diff --git a/crates/core/src/ranking/core/computer/mod.rs b/crates/core/src/ranking/core/computer/mod.rsindex c244489c..7ac030db 100644--- a/crates/core/src/ranking/core/computer/mod.rs+++ b/crates/core/src/ranking/core/computer/mod.rs@@ -60,6 +60,21 @@ pub struct TextFieldData {}impl TextFieldData {+ pub fn positions(&mut self, doc: DocId) -> Vec<Vec<u32>> {+ self.postings+ .iter_mut()+ .map(|posting| {+ if posting_contains(posting, doc) {+ let mut positions = Vec::new();+ posting.positions(&mut positions);+ positions+ } else {+ Vec::new()+ }+ })+ .collect()+ }+pub fn coverage(&mut self, doc: DocId) -> f64 {if self.postings.is_empty() {return 0.0;@@ -307,24 +322,24 @@ impl SignalComputer {let fieldnorm_reader = segment_reader.get_fieldnorms_reader(tv_field)?;let inverted_index = segment_reader.inverted_index(tv_field)?;- let mut matching_terms = Vec::with_capacity(terms.len());let mut postings = Vec::with_capacity(terms.len());for term in &terms {if let Some(p) =inverted_index.read_postings(term, text_field.record_option())?{postings.push(p);- matching_terms.push(term.clone());+ } else {+ postings.push(SegmentPostings::empty())}}let bm25 = MultiBm25Weight::for_terms(tv_searcher,- &matching_terms,+ &terms,text_field.bm25_constants(),)?;let bm25f = MultiBm25FWeight::for_terms(tv_searcher,- &matching_terms,+ &terms,text_field.bm25_constants(),);@@ -481,6 +496,17 @@ impl SignalComputer {self.segment_reader.as_ref()}+ pub fn get_field_positions(+ &mut self,+ field: TextFieldEnum,+ doc: DocId,+ ) -> Option<Vec<Vec<u32>>> {+ self.segment_reader+ .as_mut()+ .and_then(|reader| reader.get_mut().text_fields_mut().get_mut(field))+ .map(|textfield_data| textfield_data.positions(doc))+ }+pub fn fetch_time_ms_cache(&self) -> &[f64] {&self.fetch_time_ms_cache}diff --git a/crates/core/src/ranking/core/prelude.rs b/crates/core/src/ranking/core/prelude.rsindex 825b538b..164048a4 100644--- a/crates/core/src/ranking/core/prelude.rs+++ b/crates/core/src/ranking/core/prelude.rs@@ -129,6 +129,8 @@ pub enum SignalEnum {KeywordEmbeddingSimilarity,HasAds,NumQueryTerms,+ MinTitleSlop,+ MinCleanBodySlop,}enum_dispatch_from_discriminant!(SignalEnumDiscriminants => SignalEnum,@@ -177,7 +179,9 @@ enum_dispatch_from_discriminant!(SignalEnumDiscriminants => SignalEnum,TitleEmbeddingSimilarity,KeywordEmbeddingSimilarity,HasAds,- NumQueryTerms+ NumQueryTerms,+ MinTitleSlop,+ MinCleanBodySlop,]);impl SignalEnum {diff --git a/crates/core/src/ranking/core/text.rs b/crates/core/src/ranking/core/text.rsindex aa9754a4..216b9aa7 100644--- a/crates/core/src/ranking/core/text.rs+++ b/crates/core/src/ranking/core/text.rs@@ -932,3 +932,57 @@ impl Signal for KeywordEmbeddingSimilarity {None // computed in later ranking stage}}++#[derive(+ Debug,+ Clone,+ Copy,+ PartialEq,+ Eq,+ Hash,+ serde::Serialize,+ serde::Deserialize,+ bincode::Encode,+ bincode::Decode,+)]+pub struct MinTitleSlop;+impl Signal for MinTitleSlop {+ fn default_coefficient(&self) -> f64 {+ 0.1+ }++ fn as_field(&self) -> Option<Field> {+ Some(Field::Text(schema::text_field::Title.into()))+ }++ fn compute(&self, _: DocId, _: &SignalComputer) -> Option<f64> {+ None // computed in later ranking stage+ }+}++#[derive(+ Debug,+ Clone,+ Copy,+ PartialEq,+ Eq,+ Hash,+ serde::Serialize,+ serde::Deserialize,+ bincode::Encode,+ bincode::Decode,+)]+pub struct MinCleanBodySlop;+impl Signal for MinCleanBodySlop {+ fn default_coefficient(&self) -> f64 {+ 0.1+ }++ fn as_field(&self) -> Option<Field> {+ Some(Field::Text(schema::text_field::CleanBody.into()))+ }++ fn compute(&self, _: DocId, _: &SignalComputer) -> Option<f64> {+ None // computed in later ranking stage+ }+}diff --git a/crates/core/src/ranking/pipeline/mod.rs b/crates/core/src/ranking/pipeline/mod.rsindex 0062165d..367c98d2 100644--- a/crates/core/src/ranking/pipeline/mod.rs+++ b/crates/core/src/ranking/pipeline/mod.rs@@ -40,6 +40,9 @@ pub trait RankableWebpage: collector::Doc + Send + Sync {fn set_score(&mut self, score: f64);fn boost(&self) -> Option<f64>;fn signals(&self) -> &EnumMap<SignalEnum, f64>;+ fn signals_mut(&mut self) -> &mut EnumMap<SignalEnum, f64>;++ fn as_local_recall(&self) -> &LocalRecallRankingWebpage;fn boost_score(&mut self) {if let Some(boost) = self.boost() {diff --git a/crates/core/src/ranking/pipeline/scorers/embedding.rs b/crates/core/src/ranking/pipeline/scorers/embedding.rsindex 7b448063..73c834ca 100644--- a/crates/core/src/ranking/pipeline/scorers/embedding.rs+++ b/crates/core/src/ranking/pipeline/scorers/embedding.rs@@ -197,7 +197,7 @@ impl EmbeddingSignal<LocalRecallRankingWebpage> for TitleEmbeddings {fn insert_signal(webpage: &mut LocalRecallRankingWebpage, score: f64) {let sig = <TitleEmbeddings as EmbeddingSignal<LocalRecallRankingWebpage>>::signal();- webpage.mut_signals().insert(sig, score);+ webpage.signals_mut().insert(sig, score);}}@@ -235,7 +235,7 @@ impl EmbeddingSignal<LocalRecallRankingWebpage> for KeywordEmbeddings {fn insert_signal(webpage: &mut LocalRecallRankingWebpage, score: f64) {let sig = <KeywordEmbeddings as EmbeddingSignal<LocalRecallRankingWebpage>>::signal();- webpage.mut_signals().insert(sig, score);+ webpage.signals_mut().insert(sig, score);}}diff --git a/crates/core/src/ranking/pipeline/scorers/mod.rs b/crates/core/src/ranking/pipeline/scorers/mod.rsindex 624c66bd..242389d7 100644--- a/crates/core/src/ranking/pipeline/scorers/mod.rs+++ b/crates/core/src/ranking/pipeline/scorers/mod.rs@@ -18,6 +18,7 @@ pub mod embedding;pub mod inbound_similarity;pub mod recall;pub mod reranker;+pub mod term_distance;pub use recall::Recall;pub use reranker::ReRanker;diff --git a/crates/core/src/ranking/pipeline/scorers/recall.rs b/crates/core/src/ranking/pipeline/scorers/recall.rsindex dbaf5f86..b7a0820d 100644--- a/crates/core/src/ranking/pipeline/scorers/recall.rs+++ b/crates/core/src/ranking/pipeline/scorers/recall.rs@@ -31,7 +31,7 @@ use crate::{use super::{embedding::{EmbeddingScorer, KeywordEmbeddings, TitleEmbeddings},inbound_similarity::InboundScorer,- MultiScorer, Scorer,+ term_distance, MultiScorer, Scorer,};pub struct Recall<T: RankableWebpage> {@@ -70,6 +70,8 @@ impl Recall<LocalRecallRankingWebpage> {pub fn new(dual_encoder: Option<Arc<DualEncoder>>) -> Self {Self {scorer: MultiScorer::new(vec![+ Box::new(term_distance::TitleDistanceScorer),+ Box::new(term_distance::BodyDistanceScorer),Box::new(EmbeddingScorer::<LocalRecallRankingWebpage, TitleEmbeddings>::new(dual_encoder.clone(),diff --git a/crates/core/src/ranking/pipeline/scorers/term_distance.rs b/crates/core/src/ranking/pipeline/scorers/term_distance.rsnew file mode 100644index 00000000..16633cbd--- /dev/null+++ b/crates/core/src/ranking/pipeline/scorers/term_distance.rs@@ -0,0 +1,109 @@+// Stract is an open source web search engine.+// Copyright (C) 2024 Stract ApS+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++use itertools::Itertools;++use crate::ranking;+use crate::ranking::pipeline::RankableWebpage;++fn min_slop_two_positions(pos_a: &[u32], pos_b: &[u32]) -> u32 {+ let mut cur_min = u32::MAX;++ let mut cursor_a = 0;+ let mut cursor_b = 0;++ loop {+ if cursor_a >= pos_a.len() || cursor_b >= pos_b.len() {+ break;+ }++ let a = pos_a[cursor_a];+ let b = pos_b[cursor_b];++ if b > a {+ cur_min = (b - a).min(cur_min);+ cursor_a += 1;+ } else {+ cursor_b += 1;+ }+ }++ cur_min+}++fn min_slop<'a>(positions: impl Iterator<Item = &'a [u32]>) -> u32 {+ positions+ .tuple_windows()+ .map(|(a, b)| min_slop_two_positions(a, b))+ .max()+ .unwrap_or(u32::MAX)+}++#[derive(Debug, Default)]+pub struct TitleDistanceScorer;++impl TitleDistanceScorer {+ pub fn new() -> Self {+ Self+ }+}++impl<W: RankableWebpage> super::Scorer<W> for TitleDistanceScorer {+ fn score(&self, webpages: &mut [W]) {+ for webpage in webpages {+ let min_slop = min_slop(webpage.as_local_recall().iter_title_positions());++ webpage.signals_mut().insert(+ ranking::core::MinTitleSlop.into(),+ 1.0 / (min_slop as f64 + 1.0),+ );+ }+ }+}++#[derive(Debug, Default)]+pub struct BodyDistanceScorer;++impl BodyDistanceScorer {+ pub fn new() -> Self {+ Self+ }+}++impl<W: RankableWebpage> super::Scorer<W> for BodyDistanceScorer {+ fn score(&self, webpages: &mut [W]) {+ for webpage in webpages {+ let min_slop = min_slop(webpage.as_local_recall().iter_clean_body_positions());++ webpage.signals_mut().insert(+ ranking::core::MinCleanBodySlop.into(),+ 1.0 / (min_slop as f64 + 1.0),+ );+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_min_slop() {+ let positions = [vec![13, 18, 22], vec![8, 15, 30], vec![9, 16]];++ assert_eq!(min_slop(positions.iter().map(|pos| pos.as_slice())), 2);+ }+}diff --git a/crates/core/src/ranking/pipeline/stages/precision.rs b/crates/core/src/ranking/pipeline/stages/precision.rsindex dd20529a..b84f1cad 100644--- a/crates/core/src/ranking/pipeline/stages/precision.rs+++ b/crates/core/src/ranking/pipeline/stages/precision.rs@@ -77,6 +77,14 @@ impl RankableWebpage for PrecisionRankingWebpage {fn signals(&self) -> &EnumMap<SignalEnum, f64> {self.ranking.signals()}++ fn signals_mut(&mut self) -> &mut EnumMap<SignalEnum, f64> {+ self.ranking.signals_mut()+ }++ fn as_local_recall(&self) -> &super::LocalRecallRankingWebpage {+ self.ranking.as_local_recall()+ }}impl PrecisionRankingWebpage {diff --git a/crates/core/src/ranking/pipeline/stages/recall.rs b/crates/core/src/ranking/pipeline/stages/recall.rsindex d7ce249e..fd7f0507 100644--- a/crates/core/src/ranking/pipeline/stages/recall.rs+++ b/crates/core/src/ranking/pipeline/stages/recall.rs@@ -29,7 +29,7 @@ use crate::{pipeline::{RankableWebpage, RankingPipeline, RankingStage, Recall, Scorer},SignalComputer, SignalEnum,},- schema::numerical_field,+ schema::{numerical_field, text_field},searcher::{api, SearchQuery},webgraph,};@@ -77,7 +77,7 @@ impl RecallRankingWebpage {}pub fn signals_mut(&mut self) -> &mut EnumMap<SignalEnum, f64> {- self.local.mut_signals()+ self.local.signals_mut()}pub fn boost(&self) -> Option<f64> {@@ -119,12 +119,22 @@ impl RankableWebpage for RecallRankingWebpage {fn signals(&self) -> &EnumMap<SignalEnum, f64> {self.local.signals()}++ fn signals_mut(&mut self) -> &mut EnumMap<SignalEnum, f64> {+ self.local.signals_mut()+ }++ fn as_local_recall(&self) -> &LocalRecallRankingWebpage {+ &self.local+ }}#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, bincode::Encode, bincode::Decode)]pub struct LocalRecallRankingWebpage {pointer: WebpagePointer,signals: EnumMap<SignalEnum, f64>,+ title_positions: Vec<Vec<u32>>,+ clean_body_positions: Vec<Vec<u32>>,optic_boost: Option<f64>,title_embedding: Option<StoredEmbeddings>,keyword_embedding: Option<StoredEmbeddings>,@@ -142,6 +152,8 @@ impl LocalRecallRankingWebpage {LocalRecallRankingWebpage {pointer,signals,+ title_positions: Vec::new(),+ clean_body_positions: Vec::new(),optic_boost: None,title_embedding: None,keyword_embedding: None,@@ -175,6 +187,14 @@ impl LocalRecallRankingWebpage {.unwrap().into();+ let title_positions = computer+ .get_field_positions(text_field::Title.into(), pointer.address.doc_id)+ .unwrap_or_default();++ let clean_body_positions = computer+ .get_field_positions(text_field::CleanBody.into(), pointer.address.doc_id)+ .unwrap_or_default();+let mut res = LocalRecallRankingWebpage {signals: EnumMap::new(),score: pointer.score.total,@@ -182,6 +202,8 @@ impl LocalRecallRankingWebpage {pointer: pointer.clone(),title_embedding: title_embedding.map(StoredEmbeddings),keyword_embedding: keyword_embedding.map(StoredEmbeddings),+ title_positions,+ clean_body_positions,host_id,};@@ -217,7 +239,7 @@ impl LocalRecallRankingWebpage {&self.signals}- pub fn mut_signals(&mut self) -> &mut EnumMap<SignalEnum, f64> {+ pub fn signals_mut(&mut self) -> &mut EnumMap<SignalEnum, f64> {&mut self.signals}@@ -232,6 +254,14 @@ impl LocalRecallRankingWebpage {pub fn host_id(&self) -> &webgraph::NodeID {&self.host_id}++ pub fn iter_title_positions(&self) -> impl Iterator<Item = &[u32]> {+ self.title_positions.iter().map(|v| v.as_slice())+ }++ pub fn iter_clean_body_positions(&self) -> impl Iterator<Item = &[u32]> {+ self.clean_body_positions.iter().map(|v| v.as_slice())+ }}impl RankableWebpage for LocalRecallRankingWebpage {@@ -246,6 +276,14 @@ impl RankableWebpage for LocalRecallRankingWebpage {fn signals(&self) -> &EnumMap<SignalEnum, f64> {&self.signals}++ fn signals_mut(&mut self) -> &mut EnumMap<SignalEnum, f64> {+ &mut self.signals+ }++ fn as_local_recall(&self) -> &LocalRecallRankingWebpage {+ self+ }}impl collector::Doc for LocalRecallRankingWebpage {diff --git a/crates/core/src/searcher/api/mod.rs b/crates/core/src/searcher/api/mod.rsindex 91c7aeeb..1a9b5192 100644--- a/crates/core/src/searcher/api/mod.rs+++ b/crates/core/src/searcher/api/mod.rs@@ -86,12 +86,23 @@ impl RankableWebpage for ScoredWebpagePointer {self.as_ranking().boost()}+ fn as_local_recall(&self) -> &crate::ranking::pipeline::LocalRecallRankingWebpage {+ self.as_ranking().as_local_recall()+ }+fn signals(&self) -> &EnumMap<SignalEnum, f64> {match self {ScoredWebpagePointer::Normal(p) => p.website.signals(),ScoredWebpagePointer::Live(p) => p.website.signals(),}}++ fn signals_mut(&mut self) -> &mut EnumMap<SignalEnum, f64> {+ match self {+ ScoredWebpagePointer::Normal(p) => p.website.signals_mut(),+ ScoredWebpagePointer::Live(p) => p.website.signals_mut(),+ }+ }}impl collector::Doc for ScoredWebpagePointer {