Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Add per-row sample-weight support to the Rust XGB pipeline

Daoud Clarke280a1a2fae64
diff --git a/mwmbl/tinysearchengine/ltr.py b/mwmbl/tinysearchengine/ltr.py
index fc218d4..428f187 100644
--- a/mwmbl/tinysearchengine/ltr.py
+++ b/mwmbl/tinysearchengine/ltr.py
@@ -147,7 +147,7 @@ class RustXGBPipeline(BaseEstimator, RegressorMixin):
subset['score'] = subset['score'].fillna(0.0)
return subset.to_dict('records')
- def fit(self, X: DataFrame, y) -> 'RustXGBPipeline':
+ def fit(self, X: DataFrame, y, sample_weight=None) -> 'RustXGBPipeline':
"""
Train the XGBoost model.
@@ -155,6 +155,7 @@ class RustXGBPipeline(BaseEstimator, RegressorMixin):
----------
X : DataFrame with columns query, url, title, extract, score
y : array-like of float relevance labels
+ sample_weight : optional array-like of per-row weights
"""
import time
t0 = time.time()
@@ -163,11 +164,12 @@ class RustXGBPipeline(BaseEstimator, RegressorMixin):
print(f"[RustXGBPipeline.fit] Conversion done in {time.time() - t0:.2f}s. Converting labels...", flush=True)
t1 = time.time()
labels = list(np.asarray(y, dtype=np.float32))
+ weights = None if sample_weight is None else list(np.asarray(sample_weight, dtype=np.float32))
print(f"[RustXGBPipeline.fit] Labels ready in {time.time() - t1:.2f}s. Getting inner pipeline...", flush=True)
t2 = time.time()
print(f"[RustXGBPipeline.fit] Inner pipeline ready in {time.time() - t2:.2f}s. Calling Rust fit()...", flush=True)
t3 = time.time()
- self._inner.fit(records, labels)
+ self._inner.fit(records, labels, weights)
print(f"[RustXGBPipeline.fit] Rust fit() completed in {time.time() - t3:.2f}s (total: {time.time() - t0:.2f}s).", flush=True)
return self
diff --git a/mwmbl_rank/src/lib.rs b/mwmbl_rank/src/lib.rs
index 21dd7a1..75da1d4 100644
--- a/mwmbl_rank/src/lib.rs
+++ b/mwmbl_rank/src/lib.rs
@@ -91,16 +91,19 @@ impl PyXGBPipeline {
/// Args:
/// records: list of dicts with keys query, url, title, extract, score
/// labels: list of float relevance labels
+ /// sample_weight: optional list of per-row weights (default: equal weights)
///
/// Returns self (for chaining).
+ #[pyo3(signature = (records, labels, sample_weight=None))]
fn fit(
&mut self,
py: Python<'_>,
records: &Bound<'_, PyAny>,
labels: Vec<f32>,
+ sample_weight: Option<Vec<f32>>,
) -> PyResult<PyObject> {
let doc_records = self.extract_records(records)?;
- self.inner.fit(&doc_records, &labels)
+ self.inner.fit(&doc_records, &labels, sample_weight.as_deref())
.map_err(|e| PyValueError::new_err(e))?;
// Return self as a Python object for sklearn-style chaining
Ok(py.None())
diff --git a/mwmbl_rank/src/pipeline.rs b/mwmbl_rank/src/pipeline.rs
index 0e2c4d1..ae0d2f3 100644
--- a/mwmbl_rank/src/pipeline.rs
+++ b/mwmbl_rank/src/pipeline.rs
@@ -129,7 +129,13 @@ impl XGBPipeline {
///
/// `records`: list of document records (query + document fields)
/// `labels`: relevance labels (float); binarised at `self.threshold` before training
- pub fn fit(&mut self, records: &[DocumentRecord], labels: &[f32]) -> Result<(), String> {
+ /// `weights`: optional per-row sample weights (default: all rows weighted equally)
+ pub fn fit(
+ &mut self,
+ records: &[DocumentRecord],
+ labels: &[f32],
+ weights: Option<&[f32]>,
+ ) -> Result<(), String> {
use std::time::Instant;
eprintln!("[XGBPipeline::fit] Starting fit() with {} records", records.len());
@@ -144,6 +150,15 @@ impl XGBPipeline {
labels.len()
));
}
+ if let Some(w) = weights {
+ if w.len() != records.len() {
+ return Err(format!(
+ "weights length ({}) != records length ({})",
+ w.len(),
+ records.len()
+ ));
+ }
+ }
// Binarise labels at threshold (ThresholdPredictor logic)
let t0 = Instant::now();
@@ -171,6 +186,10 @@ impl XGBPipeline {
let t3 = Instant::now();
dmat.set_labels(&binary_labels)
.map_err(|e| format!("Failed to set labels: {}", e))?;
+ if let Some(w) = weights {
+ dmat.set_weights(w)
+ .map_err(|e| format!("Failed to set weights: {}", e))?;
+ }
eprintln!("[XGBPipeline::fit] DMatrix::set_labels done in {:.2?}", t3.elapsed());
// Build learning parameters (objective: binary:logistic)
@@ -333,7 +352,7 @@ mod tests {
let labels: Vec<f32> = (0..20).map(|i| if i % 2 == 0 { 1.0 } else { 0.0 }).collect();
let mut pipeline = XGBPipeline::new(0.0, 0.1, 2.0, 10);
- pipeline.fit(&records, &labels).expect("fit should succeed");
+ pipeline.fit(&records, &labels, None).expect("fit should succeed");
let preds = pipeline.predict(&records).expect("predict should succeed");
assert_eq!(preds.len(), 20);
@@ -350,7 +369,7 @@ mod tests {
let records = make_records(20);
let labels: Vec<f32> = vec![1.0; 20];
let mut pipeline = XGBPipeline::new(0.0, 0.1, 2.0, 10);
- pipeline.fit(&records, &labels).expect("fit should succeed");
+ pipeline.fit(&records, &labels, None).expect("fit should succeed");
let test = vec![
// Matches both query terms ("rust programming") -> kept.
@@ -377,6 +396,40 @@ mod tests {
assert_eq!(preds[1], 0.0, "non-matching doc should be filtered to 0.0");
}
+ #[test]
+ fn test_fit_with_weights() {
+ let records = make_records(20);
+ let labels: Vec<f32> = (0..20).map(|i| if i % 2 == 0 { 1.0 } else { 0.0 }).collect();
+
+ // Equal explicit weights must reproduce the unweighted model exactly.
+ let mut unweighted = XGBPipeline::new(0.0, 0.1, 2.0, 10);
+ unweighted.fit(&records, &labels, None).expect("fit should succeed");
+ let mut weighted = XGBPipeline::new(0.0, 0.1, 2.0, 10);
+ weighted.fit(&records, &labels, Some(&vec![1.0; 20])).expect("fit should succeed");
+ let base = unweighted.predict(&records).expect("predict should succeed");
+ let same = weighted.predict(&records).expect("predict should succeed");
+ assert_eq!(base, same, "weight=1.0 for every row must match unweighted training");
+
+ // Near-zero weight on all negative rows must push predictions up.
+ let skew: Vec<f32> = labels.iter().map(|&l| if l > 0.0 { 1.0 } else { 1e-3 }).collect();
+ let mut skewed = XGBPipeline::new(0.0, 0.1, 2.0, 10);
+ skewed.fit(&records, &labels, Some(&skew)).expect("fit should succeed");
+ let up = skewed.predict(&records).expect("predict should succeed");
+ let mean = |v: &[f32]| v.iter().sum::<f32>() / v.len() as f32;
+ assert!(mean(&up) > mean(&base),
+ "down-weighting negatives should raise mean prediction ({} vs {})",
+ mean(&up), mean(&base));
+ }
+
+ #[test]
+ fn test_fit_rejects_mismatched_weights() {
+ let records = make_records(10);
+ let labels = vec![1.0; 10];
+ let mut pipeline = XGBPipeline::new(0.0, 0.1, 2.0, 5);
+ let result = pipeline.fit(&records, &labels, Some(&vec![1.0; 3]));
+ assert!(result.is_err());
+ }
+
#[test]
fn test_pipeline_predict_without_fit() {
let records = make_records(5);
@@ -390,7 +443,7 @@ mod tests {
let records = make_records(10);
let labels: Vec<f32> = vec![1.0; 10];
let mut pipeline = XGBPipeline::new(0.0, 0.1, 2.0, 5);
- pipeline.fit(&records, &labels).expect("fit should succeed");
+ pipeline.fit(&records, &labels, None).expect("fit should succeed");
let preds = pipeline.predict(&[]).expect("empty predict should succeed");
assert_eq!(preds.len(), 0);