Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 55 additions & 2 deletions crates/pyspark-rs/src/ml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,6 @@ pub use evaluation::{
pub(crate) mod feature;
pub(crate) mod feature_api;

pub(crate) mod recommendation;

use crate::dataframe::PyDataFrame;
use crate::errors::ResultExt;
use crate::interrupt::interruptible;
Expand Down Expand Up @@ -305,6 +303,7 @@ macro_rules! native {
}

pub(crate) mod fpm;
pub(crate) mod recommendation;

/// Set the param `name` of `target` to `value`.
fn apply<T: Native>(target: &mut T, name: &'static str, value: Converted) {
Expand Down Expand Up @@ -673,6 +672,60 @@ where
object::ModelObject::into_object(model, py)
}

/// Fit an estimator whose Python subclass can override the model factory or parameter copying.
/// The standard factory produces a typed native model. A custom factory takes ownership of the
/// fitted reference after it has successfully constructed its Python model.
fn fit_with_model_factory<T, M>(
slf: &Bound<'_, T>,
dataset: &Bound<'_, PyAny>,
params: Option<&Bound<'_, PyAny>>,
make_model: impl FnOnce(Python<'_>, Box<dyn Model>, &DataFrame) -> PyResult<M>,
) -> PyResult<Fitted<Py<PyAny>>>
where
T: Native + PyClass<Frozen = False>,
T::Core: Estimator,
M: params_api::ParamsHolder + pyo3::PyTypeInfo + object::ModelObject,
{
fit_with(slf, dataset, params, || {
if !has_custom_model_hooks(slf)? {
return fit_native_model(slf, dataset, make_model).map(Py::into_any);
}
let py = slf.py();
let df = dataset_of(dataset, "fit")?;
let trained = run_estimator_fit(py, &mut snapshot(slf)?, &df)?;
let object = trained.ml_ref().ok_or_else(|| {
pyo3::exceptions::PyRuntimeError::new_err("The fitted model has no server reference")
})?;
let reference = object::remote_model_ref(py, object.id())?;
let slf = slf.as_any();
let model = slf.call_method1("_create_model", (reference,))?;
object.keep();
model.call_method1("_resetUid", (slf.getattr("uid")?,))?;
Ok(slf.call_method1("_copyValues", (model,))?.unbind())
})
}

fn has_custom_model_hooks<T: PyClass>(slf: &Bound<'_, T>) -> PyResult<bool> {
let Some(class) = object::public_class::<T>(slf.py()) else {
return Ok(false);
};
let slf = slf.as_any();
if !slf.is_instance(&class)? {
return Ok(false);
}
for name in ["_create_model", "_copyValues"] {
let default = class.getattr(name)?;
let method = slf.getattr(name)?;
if !method
.getattr_opt("__func__")?
.is_some_and(|f| f.is(&default))
{
return Ok(true);
}
}
Ok(false)
}

/// Run a fit on the Rust estimator while retaining any resources used by the input plan.
fn run_estimator_fit(
py: Python<'_>,
Expand Down
42 changes: 2 additions & 40 deletions crates/pyspark-rs/src/ml/fpm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,30 +30,6 @@ pub struct PyFPGrowth {

native!(PyFPGrowth => FPGrowth { defaults: own_defaults });

impl PyFPGrowth {
// The default factory returns the typed native model. Python overrides can return another
// model class or customize the parameters copied onto the result.
fn has_custom_model_hooks(slf: &Bound<'_, Self>) -> PyResult<bool> {
let Some(class) = object::public_class::<Self>(slf.py()) else {
return Ok(false);
};
if !slf.is_instance(&class)? {
return Ok(false);
}
for name in ["_create_model", "_copyValues"] {
let default = class.getattr(name)?;
let method = slf.getattr(name)?;
if !method
.getattr_opt("__func__")?
.is_some_and(|f| f.is(&default))
{
return Ok(true);
}
}
Ok(false)
}
}

native_pymethods! {
PyFPGrowth;
jvm: "org.apache.spark.ml.fpm.FPGrowth", op: Estimator;
Expand Down Expand Up @@ -142,22 +118,8 @@ native_pymethods! {
dataset: &Bound<'_, PyAny>,
params: Option<&Bound<'_, PyAny>>,
) -> PyResult<Fitted<Py<PyAny>>> {
fit_with(slf, dataset, params, || {
if Self::has_custom_model_hooks(slf)? {
let py = slf.py();
let df = dataset_of(dataset, "fit")?;
let trained = run_estimator_fit(py, &mut snapshot(slf)?, &df)?;
let object = trained.ml_ref().expect("FPGrowth fits a cached model");
let reference = object::remote_model_ref(py, object.id())?;
let model = slf.call_method1("_create_model", (reference,))?;
// The custom wrapper now owns the server reference.
object.keep();
model.call_method1("_resetUid", (slf.getattr("uid")?,))?;
return Ok(slf.call_method1("_copyValues", (model,))?.unbind());
}
fit_native_model(slf, dataset, |py, model, df| {
PyFPGrowthModel::fitted(py, model, df, object::SummaryDataset::None)
}).map(Py::into_any)
fit_with_model_factory(slf, dataset, params, |py, model, df| {
PyFPGrowthModel::fitted(py, model, df, object::SummaryDataset::None)
})
}

Expand Down
49 changes: 23 additions & 26 deletions crates/pyspark-rs/src/ml/recommendation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,28 +28,10 @@ const ALS_PARAMS: &[(&str, Kind)] = &[
pub struct PyALS {
inner: ALS,
unsendable: Vec<&'static str>,
own_defaults: params_api::OwnDefaults,
gc_ready: crate::gc::GcReady,
}
impl Native for PyALS {
type Core = ALS;
fn inner(&self) -> &Self::Core {
&self.inner
}
fn core_params_mut(core: &mut Self::Core) -> &mut Params {
core.params_mut()
}
fn params(&self) -> &Params {
self.inner.params()
}
fn params_mut(&mut self) -> &mut Params {
self.inner.params_mut()
}
fn unsendable(&self) -> &[&'static str] {
&self.unsendable
}
fn unsendable_mut(&mut self) -> &mut Vec<&'static str> {
&mut self.unsendable
}
}
native!(PyALS => ALS { defaults: own_defaults });

native_pymethods! {
PyALS;
Expand Down Expand Up @@ -96,10 +78,25 @@ native_pymethods! {
let mut this = Self {
inner: ALS::new(),
unsendable: Vec::new(),
own_defaults: Vec::new(),
gc_ready: crate::gc::GcReady::new(),
};
init_params(&mut this, "ALS", &[], ALS_PARAMS, args, kwargs)?;
Ok(this)
}
fn __traverse__(&self, visit: pyo3::PyVisit<'_>) -> Result<(), pyo3::PyTraverseError> {
if !self.gc_ready.get() {
return Ok(());
}
params_api::visit_values(&self.own_defaults, &visit)
}

fn __clear__(&mut self) {
if self.gc_ready.get() {
self.own_defaults.clear();
}
}

#[pyo3(
name = "setParams",
signature = (*args, **kwargs),
Expand Down Expand Up @@ -258,11 +255,9 @@ native_pymethods! {
slf: &Bound<'_, Self>,
dataset: &Bound<'_, PyAny>,
params: Option<&Bound<'_, PyAny>>,
) -> PyResult<Fitted<Py<PyALSModel>>> {
fit_with(slf, dataset, params, || {
fit_native_model(slf, dataset, |py, model, df| {
PyALSModel::fitted(py, model, df, object::SummaryDataset::None)
})
) -> PyResult<Fitted<Py<PyAny>>> {
fit_with_model_factory(slf, dataset, params, |py, model, df| {
PyALSModel::fitted(py, model, df, object::SummaryDataset::None)
})
}

Expand All @@ -286,6 +281,8 @@ impl params_api::NativeInstance for PyALS {
Self {
inner: self.inner.clone(),
unsendable: self.unsendable.clone(),
own_defaults: params_api::clone_own_defaults(py, &self.own_defaults),
gc_ready: crate::gc::GcReady::new(),
},
)
}
Expand Down
54 changes: 5 additions & 49 deletions crates/spark-connect/src/ml/recommendation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,50 +114,11 @@ impl ALSModel {
cached,
})
}
fn fetch(
&self,
method: &str,
args: Vec<proto::fetch::method::Args>,
input: Option<&DataFrame>,
) -> spark_connect_core::error::Result<DataFrame> {
let relation = proto::Relation {
rel_type: Some(proto::relation::RelType::MlRelation(Box::new(
proto::MlRelation {
ml_type: Some(proto::ml_relation::MlType::Fetch(proto::Fetch {
obj_ref: Some(self.cached.0.model_ref.clone()),
methods: vec![proto::fetch::Method {
method: method.into(),
args,
}],
})),
..Default::default()
},
))),
..Default::default()
};
if let Some(df) = input {
Ok(DataFrame::new(
self.cached.0.session.clone(),
LogicalPlan::MlTransform {
ml_relation: Box::new(relation),
input: df.plan.clone(),
owner: Some(RelationOwner(self.cached.0.clone())),
input_at: crate::plan::MlInputAt::Nowhere,
},
))
} else {
DataFrame::from_relation(
self.cached.0.session.clone(),
relation,
Some(self.cached.0.clone()),
)
}
}
pub fn user_factors(&self) -> spark_connect_core::error::Result<DataFrame> {
self.fetch("userFactors", Vec::new(), None)
attribute_relation(&MlTarget::object(&self.cached), "userFactors", vec![])
}
pub fn item_factors(&self) -> spark_connect_core::error::Result<DataFrame> {
self.fetch("itemFactors", Vec::new(), None)
attribute_relation(&MlTarget::object(&self.cached), "itemFactors", vec![])
}
/// Binding seam that preserves the literal type of Python recommendation-count arguments.
#[doc(hidden)]
Expand All @@ -167,28 +128,23 @@ impl ALSModel {
subset: Option<&DataFrame>,
count: proto::expression::Literal,
) -> spark_connect_core::error::Result<DataFrame> {
use proto::fetch::method::args::ArgsType;
let mut args = Vec::new();
if let Some(df) = subset {
if df.session.session_id() != self.cached.0.session.session_id() {
return Err(spark_connect_core::error::SparkError::value_msg(
"A fitted ML model must recommend data from its fitting session",
));
}
args.push(proto::fetch::method::Args {
args_type: Some(ArgsType::Input(df.relation()?)),
});
args.push(FetchArg::Input(df.clone()));
}
args.push(proto::fetch::method::Args {
args_type: Some(ArgsType::Param(count)),
});
args.push(FetchArg::Literal(count));
let method = match (users, subset.is_some()) {
(true, false) => "recommendForAllUsers",
(false, false) => "recommendForAllItems",
(true, true) => "recommendForUserSubset",
(false, true) => "recommendForItemSubset",
};
self.fetch(method, args, subset)
attribute_relation(&MlTarget::object(&self.cached), method, args)
}
pub fn recommend_for_all_users(
&self,
Expand Down
9 changes: 5 additions & 4 deletions docs/compatibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -2242,8 +2242,8 @@ client:
## pyspark.ml

The DataFrame-based `pyspark.ml` API follows Apache Spark v4.3.0. The standard
classification and regression estimators, all five clustering algorithms, and both
frequent-pattern algorithms delegate ML operations to the Rust API.
classification and regression estimators, all five clustering algorithms, both
frequent-pattern algorithms, and ALS delegate ML operations to the Rust API.
Operations implemented by the vendored Python ML code build their `spark.connect` messages with
`pyspark.sql.connect.proto`, which is the drop-in's own protobuf runtime in Rust
(`pyspark.sql.connect.proto._rust`) in place of the generated modules of Apache Spark, whether or
Expand Down Expand Up @@ -5427,8 +5427,9 @@ predictions, model setters, sequence-length limits, invalid data, and model life

## Native ALS recommendation

`ml::ALS` / `ml::ALSModel` in Rust and `pyspark.ml.connect.recommendation.ALS` /
`ALSModel` in the Rust-backed Python package run Spark's standard ALS over Connect.
The standard Python classes `pyspark.ml.recommendation.ALS` and `ALSModel` delegate
fit, transform, model access, recommendations and persistence to Rust. Setting Python
parameters updates native state immediately. The compatibility import exposes the same classes.
The estimator exposes all 18 parameters, including explicit/implicit feedback,
nonnegative factors, regularization, block counts, storage levels and seed.
Python mirrors the 17 official constructor keywords; use `setPredictionCol` for
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ extend-exclude = [
"python/pyspark/ml/image.py",
"python/pyspark/ml/model_cache.py",
"python/pyspark/ml/pipeline.py",
"python/pyspark/ml/recommendation.py",
"python/pyspark/ml/_upstream/recommendation.py",
"python/pyspark/ml/_upstream/regression.py",
"python/pyspark/ml/tree.py",
"python/pyspark/ml/tuning.py",
Expand Down
Loading
Loading