This is an automated email from the ASF dual-hosted git repository.

HyukjinKwon pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark-connect-rust.git


The following commit(s) were added to refs/heads/master by this push:
     new 7151ef5b [SPARK-61238][CONNECT][PYTHON] Fit the ML Connect scalers and 
indexers on the server, and add the ML cache queries as PySpark does
7151ef5b is described below

commit 7151ef5b974e5c46df11190e5318364c64e0ad50
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Mon Nov 9 21:35:31 2026 +0900

    [SPARK-61238][CONNECT][PYTHON] Fit the ML Connect scalers and indexers on 
the server, and add the ML cache queries as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61238](https://issues.apache.org/jira/browse/SPARK-61238): Fit the 
native `StandardScaler`, `MaxAbsScaler` and `StringIndexer` on the server, and 
add the ML cache queries of the client.
    
    - The Rust core fits `StandardScaler`, `MaxAbsScaler` and `StringIndexer` 
through `MlCommand.Fit`, as `LogisticRegression` and `LinearSVC` already do. 
Their models hold the server's cached model, and their transform sends 
`MlRelation.Transform.obj_ref`, as PySpark's fitted models do in 
`pyspark/ml/connect/proto.py` (`TransformerRelation(is_model=True)`). Before, 
the models were built locally and their transform sent a transformer of type 
`MODEL`, which the server rejects.
    - `SparkConnectClient._get_ml_cache_info` sends `MlCommand.get_cache_info` 
and returns the JSON of the cached objects, and `_query_model_size` sends 
`MlCommand.get_model_size`, both as `pyspark/sql/connect/client/core.py` does.
    - Official PySpark 4.3.0 gives the same values for `StandardScaler`, 
`MaxAbsScaler` and `StringIndexer` fit and transform on `array_to_vector` 
features (for example `[1.0, 2.0]` and `[0.3333..., 0.6666...]`). The scalers 
take ML vector features, as the server requires.
    - Not changed, and out of scope here: the native `Pipeline` and 
`CrossValidator` still fit locally, and their transform sends a transformer of 
type `MODEL`, so they fail on the server as before (see below).
    - Rust API change: the models of these three estimators no longer have 
public `input_col`/`output_col` fields (they were never read), and their 
constructors are private to the module.
    
    ### Not covered (follow-up needed, native API redesign)
    
    Checked live on port 15018 with master's build (`scr-sweep`) and with this 
build; results are identical:
    - `Pipeline(stages=["StandardScaler", 
"LogisticRegression"]).fit(df).transform(df)` fails with `UnknownException: 
(java.lang.AssertionError)` in `MLHandler._transformMLRelation` (the 
transformer of type `MODEL`). `fit` alone returns without a server call. 
`Pipeline(stages=[StandardScaler(...), LogisticRegression(...)])` raises 
`TypeError: argument 'stages': 'StandardScaler' object is not an instance of 
'str'`, because the native `Pipeline` takes stage names only.
    - `CrossValidator(numFolds=2).fit(df).transform(df)` fails with the same 
assertion. `CrossValidator` takes no `estimator`, `evaluator` or param grid 
(`TypeError: unexpected keyword argument 'estimator'`), and its `fit` builds a 
model without a fitted sub-model.
    A fix needs the native `Pipeline` to take stage objects, fit them in order 
on the client (the stage models, then `df = model.transform(df)`), and make the 
`PipelineModel` transform through each stage's cached model. `CrossValidator` 
needs the estimator, the evaluator and the param maps. Both change the public 
Rust and PyO3 signatures, so they are a separate PR.
    
    ### Why are the changes needed?
    
    With the native API, `StandardScaler(inputCol="v", 
outputCol="o").fit(df).transform(df)` failed on the server with 
`UnknownException: (java.lang.AssertionError) assertion failed ... 
MLHandler$._transformMLRelation`, for array, vector and double inputs alike. 
The fit did not reach the server, so there was no model to transform. 
`SparkSession._client._get_ml_cache_info()` and `_query_model_size()` raised 
`AttributeError`, and the official 
`pyspark/ml/tests/connect/test_connect_cache.py` [...]
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. Fitting `StandardScaler`, `MaxAbsScaler` and `StringIndexer` of 
`pyspark.ml.connect` now runs on the server, and their transform works. The 
Python client gains `_get_ml_cache_info` and `_query_model_size`.
    
    ### How was this patch tested?
    
    - Offline Rust: `transform_and_fit_build_ml_transform_plans` (the transform 
of a scaler refers to its cached model's object reference) and 
`offline_estimators_fit_and_models_transform` (the same for `MaxAbsScaler` and 
`StringIndexer`, plus `test_all_transformer_types`).
    - Live Rust: `e2e_coverage::ml_estimators_and_transformers` now asserts 
that the fits and transforms succeed on a server, instead of tolerating a 
rejection.
    - Offline Python, `test_ml_cache_queries_are_those_of_pyspark`: the 
`get_cache_info` and `get_model_size` commands and their results. 
`test_ml_connect_fitted_scalers_transform_the_cached_model`: the fit command of 
each scaler and indexer, and a transform that refers to the fitted object.
    - Live Python, `test_ml_connect_scalers_fit_and_transform_as_pyspark`: the 
values of the three estimators on `array_to_vector` features, which give the 
values of PySpark 4.3.0.
    - The official `pyspark/ml/tests/connect/test_connect_cache.py` now passes 
4 of 4 (was 2 of 4) and `test_connect_model_offloading.py` passes 6 of 6 (was 2 
of 6). The official `test_parity_*.py` files of `pyspark/ml/tests/connect` pass 
140 tests, as on master.
    - The tests of both crates against a local Spark 4.3.0 Connect server (793 
and 186 passed), the build of all tests, also with `wasm-udf`, the offline 
Python suites (2821 passed, 8 skipped), and the live drop-in, Arrow and ML 
suites (234 passed) and live cases (13 passed). rustfmt and ruff pass, and 
clippy reports no diagnostics in the changed lines. The official 
`ml/tests/connect/test_connect_cache.py` (4 passed) and 
`test_connect_model_offloading.py` (6 passed) pass against the drop- [...]
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5 and Claude Haiku 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #418 from HyukjinKwon/SPARK-61238-ml-server-fit.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/spark-connect/src/ml.rs                  | 245 ++++++++++++++----------
 crates/spark-connect/tests/coverage_ml_extra.rs |  29 +--
 crates/spark-connect/tests/e2e_coverage.rs      |  29 +--
 crates/spark-connect/tests/ml_extra_golden.rs   |  34 +---
 python/pyspark/sql/connect/client/__init__.py   |  25 +++
 python/tests/test_ml_e2e.py                     |  25 +++
 python/tests/test_ml_offline.py                 |  59 ++++++
 7 files changed, 279 insertions(+), 167 deletions(-)

diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index 0d2da7f5..824c1f11 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -401,6 +401,23 @@ impl StandardScaler {
     pub fn output_col(&self) -> &str {
         &self.output_col
     }
+
+    fn model_from_info(
+        &self,
+        info: proto::ml_command_result::MlOperatorInfo,
+        session: &SparkSession,
+    ) -> spark_connect_core::error::Result<StandardScalerModel> {
+        let cached = CachedModel::from_info(&info, session, "StandardScaler")?;
+        Ok(StandardScalerModel {
+            operator: MlOperator::with_uid(
+                "org.apache.spark.ml.feature.StandardScalerModel",
+                info.uid.as_deref().unwrap_or(&self.operator.uid),
+                OperatorType::Model,
+            ),
+            params: self.params.clone(),
+            cached,
+        })
+    }
 }
 
 impl Default for StandardScaler {
@@ -426,25 +443,20 @@ impl Estimator for StandardScaler {
         &mut self.params
     }
 
-    fn fit_impl(&mut self, _df: &DataFrame) -> 
spark_connect_core::error::Result<Box<dyn Model>> {
-        // Create a StandardScalerModel from this estimator
-        let model = StandardScalerModel {
-            operator: MlOperator::with_uid(
-                &self.operator.name,
-                &self.operator.uid,
-                OperatorType::Model,
-            ),
-            params: self.params.clone(),
-        };
-        Ok(Box::new(model))
+    fn fit_impl(&mut self, df: &DataFrame) -> 
spark_connect_core::error::Result<Box<dyn Model>> {
+        // The server fits the scaler and caches the model, as PySpark does.
+        let info = fit_via_command(&self.operator, &self.params, df)?;
+        Ok(Box::new(self.model_from_info(info, &df.session)?))
     }
 }
 
-/// StandardScalerModel: fitted model from StandardScaler.
+/// StandardScalerModel: a StandardScaler fitted by Spark Connect and cached 
for its fitting
+/// session. Its transform refers to the cached model, as a fitted PySpark 
model's does.
 #[derive(Debug, Clone)]
 pub struct StandardScalerModel {
     operator: MlOperator,
     params: Params,
+    cached: CachedModel,
 }
 
 impl Transformer for StandardScalerModel {
@@ -464,23 +476,12 @@ impl Transformer for StandardScalerModel {
         &mut self.params
     }
 
-    fn transform_impl(&mut self, df: &DataFrame) -> 
spark_connect_core::error::Result<DataFrame> {
-        // Build an MlRelation for transformation
-        let ml_relation = self.build_ml_relation(df);
-
-        // Wrap it in a Relation
-        let mut relation = proto::Relation::default();
-        relation.common = Some(proto::RelationCommon::default());
-        relation.rel_type = 
Some(proto::relation::RelType::MlRelation(Box::new(ml_relation)));
-
-        // Wrap the built MlRelation as the plan; its `to_proto` emits the 
relation as-is.
-        let plan = LogicalPlan::MlTransform {
-            ml_relation: relation,
-            input: df.plan.clone(),
-            owner: None,
-        };
+    fn build_ml_relation(&self, input: &DataFrame) -> proto::MlRelation {
+        self.cached.build_ml_relation(input, &self.params)
+    }
 
-        Ok(DataFrame::new(df.session.clone(), plan))
+    fn transform_impl(&mut self, df: &DataFrame) -> 
spark_connect_core::error::Result<DataFrame> {
+        self.cached.transform(df, &self.params)
     }
 }
 
@@ -613,6 +614,23 @@ impl StringIndexer {
     pub fn output_col(&self) -> &str {
         &self.output_col
     }
+
+    fn model_from_info(
+        &self,
+        info: proto::ml_command_result::MlOperatorInfo,
+        session: &SparkSession,
+    ) -> spark_connect_core::error::Result<StringIndexerModel> {
+        let cached = CachedModel::from_info(&info, session, "StringIndexer")?;
+        Ok(StringIndexerModel {
+            operator: MlOperator::with_uid(
+                "org.apache.spark.ml.feature.StringIndexerModel",
+                info.uid.as_deref().unwrap_or(&self.operator.uid),
+                OperatorType::Model,
+            ),
+            params: self.params.clone(),
+            cached,
+        })
+    }
 }
 
 impl Default for StringIndexer {
@@ -638,28 +656,20 @@ impl Estimator for StringIndexer {
         &mut self.params
     }
 
-    fn fit_impl(&mut self, _df: &DataFrame) -> 
spark_connect_core::error::Result<Box<dyn Model>> {
-        let model = StringIndexerModel {
-            operator: MlOperator::with_uid(
-                &self.operator.name,
-                &self.operator.uid,
-                OperatorType::Model,
-            ),
-            params: self.params.clone(),
-            input_col: self.input_col.clone(),
-            output_col: self.output_col.clone(),
-        };
-        Ok(Box::new(model))
+    fn fit_impl(&mut self, df: &DataFrame) -> 
spark_connect_core::error::Result<Box<dyn Model>> {
+        // The server fits the indexer and caches the model, as PySpark does.
+        let info = fit_via_command(&self.operator, &self.params, df)?;
+        Ok(Box::new(self.model_from_info(info, &df.session)?))
     }
 }
 
-/// StringIndexerModel: fitted model from StringIndexer.
+/// StringIndexerModel: a StringIndexer fitted by Spark Connect and cached for 
its fitting
+/// session. Its transform refers to the cached model, as a fitted PySpark 
model's does.
 #[derive(Debug, Clone)]
 pub struct StringIndexerModel {
     pub operator: MlOperator,
     pub params: Params,
-    pub input_col: String,
-    pub output_col: String,
+    cached: CachedModel,
 }
 
 impl Transformer for StringIndexerModel {
@@ -679,17 +689,12 @@ impl Transformer for StringIndexerModel {
         &mut self.params
     }
 
+    fn build_ml_relation(&self, input: &DataFrame) -> proto::MlRelation {
+        self.cached.build_ml_relation(input, &self.params)
+    }
+
     fn transform_impl(&mut self, df: &DataFrame) -> 
spark_connect_core::error::Result<DataFrame> {
-        let ml_relation = self.build_ml_relation(df);
-        let mut relation = proto::Relation::default();
-        relation.common = Some(proto::RelationCommon::default());
-        relation.rel_type = 
Some(proto::relation::RelType::MlRelation(Box::new(ml_relation)));
-        let plan = LogicalPlan::MlTransform {
-            ml_relation: relation,
-            input: df.plan.clone(),
-            owner: None,
-        };
-        Ok(DataFrame::new(df.session.clone(), plan))
+        self.cached.transform(df, &self.params)
     }
 }
 
@@ -740,6 +745,23 @@ impl MaxAbsScaler {
     pub fn output_col(&self) -> &str {
         &self.output_col
     }
+
+    fn model_from_info(
+        &self,
+        info: proto::ml_command_result::MlOperatorInfo,
+        session: &SparkSession,
+    ) -> spark_connect_core::error::Result<MaxAbsScalerModel> {
+        let cached = CachedModel::from_info(&info, session, "MaxAbsScaler")?;
+        Ok(MaxAbsScalerModel {
+            operator: MlOperator::with_uid(
+                "org.apache.spark.ml.feature.MaxAbsScalerModel",
+                info.uid.as_deref().unwrap_or(&self.operator.uid),
+                OperatorType::Model,
+            ),
+            params: self.params.clone(),
+            cached,
+        })
+    }
 }
 
 impl Default for MaxAbsScaler {
@@ -765,28 +787,20 @@ impl Estimator for MaxAbsScaler {
         &mut self.params
     }
 
-    fn fit_impl(&mut self, _df: &DataFrame) -> 
spark_connect_core::error::Result<Box<dyn Model>> {
-        let model = MaxAbsScalerModel {
-            operator: MlOperator::with_uid(
-                &self.operator.name,
-                &self.operator.uid,
-                OperatorType::Model,
-            ),
-            params: self.params.clone(),
-            input_col: self.input_col.clone(),
-            output_col: self.output_col.clone(),
-        };
-        Ok(Box::new(model))
+    fn fit_impl(&mut self, df: &DataFrame) -> 
spark_connect_core::error::Result<Box<dyn Model>> {
+        // The server fits the scaler and caches the model, as PySpark does.
+        let info = fit_via_command(&self.operator, &self.params, df)?;
+        Ok(Box::new(self.model_from_info(info, &df.session)?))
     }
 }
 
-/// MaxAbsScalerModel: fitted model from MaxAbsScaler.
+/// MaxAbsScalerModel: a MaxAbsScaler fitted by Spark Connect and cached for 
its fitting
+/// session. Its transform refers to the cached model, as a fitted PySpark 
model's does.
 #[derive(Debug, Clone)]
 pub struct MaxAbsScalerModel {
     pub operator: MlOperator,
     pub params: Params,
-    pub input_col: String,
-    pub output_col: String,
+    cached: CachedModel,
 }
 
 impl Transformer for MaxAbsScalerModel {
@@ -806,17 +820,12 @@ impl Transformer for MaxAbsScalerModel {
         &mut self.params
     }
 
+    fn build_ml_relation(&self, input: &DataFrame) -> proto::MlRelation {
+        self.cached.build_ml_relation(input, &self.params)
+    }
+
     fn transform_impl(&mut self, df: &DataFrame) -> 
spark_connect_core::error::Result<DataFrame> {
-        let ml_relation = self.build_ml_relation(df);
-        let mut relation = proto::Relation::default();
-        relation.common = Some(proto::RelationCommon::default());
-        relation.rel_type = 
Some(proto::relation::RelType::MlRelation(Box::new(ml_relation)));
-        let plan = LogicalPlan::MlTransform {
-            ml_relation: relation,
-            input: df.plan.clone(),
-            owner: None,
-        };
-        Ok(DataFrame::new(df.session.clone(), plan))
+        self.cached.transform(df, &self.params)
     }
 }
 
@@ -2143,14 +2152,12 @@ mod tests {
             Box::new(StringIndexerModel {
                 operator: MlOperator::new("test", OperatorType::Model),
                 params: Params::new(),
-                input_col: "in".to_string(),
-                output_col: "out".to_string(),
+                cached: cached_model(&offline_session(), "indexer-1"),
             }),
             Box::new(MaxAbsScalerModel {
                 operator: MlOperator::new("test", OperatorType::Model),
                 params: Params::new(),
-                input_col: "in".to_string(),
-                output_col: "out".to_string(),
+                cached: cached_model(&offline_session(), "max-abs-1"),
             }),
         ];
 
@@ -2207,6 +2214,37 @@ mod tests {
             .expect("session")
     }
 
+    /// The model that a fit of the server returns as the object `id`, cached 
for `s`.
+    fn cached_model(s: &SparkSession, id: &str) -> CachedModel {
+        let info = proto::ml_command_result::MlOperatorInfo {
+            r#type: 
Some(proto::ml_command_result::ml_operator_info::Type::ObjRef(
+                proto::ObjectRef { id: id.to_string() },
+            )),
+            uid: Some("uid".to_string()),
+            ..Default::default()
+        };
+        CachedModel::from_info(&info, s, "test").expect("cached model")
+    }
+
+    /// The object reference of the model that the transform of `df` refers to.
+    fn transform_model_ref(df: &DataFrame) -> String {
+        let LogicalPlan::MlTransform { ml_relation, .. } = df.plan.as_ref() 
else {
+            panic!("expected an ML transform plan");
+        };
+        let Some(proto::relation::RelType::MlRelation(ml)) = 
&ml_relation.rel_type else {
+            panic!("expected an ML relation");
+        };
+        let Some(proto::ml_relation::MlType::Transform(transform)) = 
&ml.ml_type else {
+            panic!("expected a transform");
+        };
+        match &transform.operator {
+            Some(proto::ml_relation::transform::Operator::ObjRef(reference)) 
=> {
+                reference.id.clone()
+            }
+            other => panic!("expected the model reference, found {other:?}"),
+        }
+    }
+
     #[test]
     fn params_int_and_proto_roundtrip() {
         let p = Params::new()
@@ -2257,17 +2295,23 @@ mod tests {
         let out = va.transform(&df).unwrap();
         assert!(matches!(out.plan.as_ref(), LogicalPlan::MlTransform { .. }));
 
-        // StandardScaler fits locally into a model; the model transform also 
builds
-        // an MlTransform plan, and Model::clone_box works.
-        let mut ss = StandardScaler::new()
+        // A fitted StandardScaler transforms through the model that the 
server cached: the
+        // transform refers to its object reference, as PySpark's transform of 
a fitted
+        // model does. The fit itself needs a server, so the cached model is 
built here.
+        let ss = StandardScaler::new()
             .set_input_col("features")
             .set_output_col("scaled");
-        let mut model = ss.fit(&df).unwrap();
+        let mut model = StandardScalerModel {
+            operator: MlOperator::new("test", OperatorType::Model),
+            params: ss.params().clone(),
+            cached: cached_model(&s, "scaler-1"),
+        };
         let scaled = model.transform(&df).unwrap();
         assert!(matches!(
             scaled.plan.as_ref(),
             LogicalPlan::MlTransform { .. }
         ));
+        assert_eq!(transform_model_ref(&scaled), "scaler-1");
         let _cloned = model.clone_box();
     }
 
@@ -2322,21 +2366,28 @@ mod tests {
     fn offline_estimators_fit_and_models_transform() {
         let s = offline_session();
         let df = s.range(3).unwrap();
-        // Each estimator fits locally and its model transform builds a plan; 
this
-        // exercises the offline model wrappers. LogisticRegression is tested 
against a server.
-        let mut mas = 
MaxAbsScaler::new().set_input_col("f").set_output_col("o");
+        // The models of the server-fitted estimators transform through their 
cached model;
+        // this exercises the offline model wrappers. The fits are tested 
against a server.
+        let mas = MaxAbsScaler::new().set_input_col("f").set_output_col("o");
         assert_eq!(mas.input_col(), "f");
-        let mut m = mas.fit(&df).unwrap();
-        assert!(matches!(
-            m.transform(&df).unwrap().plan.as_ref(),
-            LogicalPlan::MlTransform { .. }
-        ));
+        let mut m = MaxAbsScalerModel {
+            operator: MlOperator::new("test", OperatorType::Model),
+            params: mas.params().clone(),
+            cached: cached_model(&s, "max-abs-1"),
+        };
+        let out = m.transform(&df).unwrap();
+        assert_eq!(transform_model_ref(&out), "max-abs-1");
         let _ = m.clone_box();
 
-        let mut si = 
StringIndexer::new().set_input_col("s").set_output_col("si");
+        let si = StringIndexer::new().set_input_col("s").set_output_col("si");
         assert_eq!(si.output_col(), "si");
-        let mut m = si.fit(&df).unwrap();
-        let _ = m.transform(&df).unwrap();
+        let mut m = StringIndexerModel {
+            operator: MlOperator::new("test", OperatorType::Model),
+            params: si.params().clone(),
+            cached: cached_model(&s, "indexer-1"),
+        };
+        let out = m.transform(&df).unwrap();
+        assert_eq!(transform_model_ref(&out), "indexer-1");
         let _ = m.clone_box();
 
         let mut pipe = Pipeline::new().set_stages(vec!["a", "b"]);
diff --git a/crates/spark-connect/tests/coverage_ml_extra.rs 
b/crates/spark-connect/tests/coverage_ml_extra.rs
index f785ec66..77577f68 100644
--- a/crates/spark-connect/tests/coverage_ml_extra.rs
+++ b/crates/spark-connect/tests/coverage_ml_extra.rs
@@ -9,9 +9,9 @@
 
 use spark_connect::ml::{
     BinaryClassificationEvaluator, CrossValidator, Estimator, Evaluator, 
LogisticRegression,
-    MaxAbsScaler, MaxAbsScalerModel, MlOperator, Model, 
MulticlassClassificationEvaluator,
-    OperatorType, Params, Pipeline, PipelineModel, RegressionEvaluator, 
StandardScaler,
-    StringIndexer, StringIndexerModel, Transformer, VectorAssembler,
+    MaxAbsScaler, MlOperator, Model, MulticlassClassificationEvaluator, 
OperatorType, Params,
+    Pipeline, PipelineModel, RegressionEvaluator, StandardScaler, 
StringIndexer, Transformer,
+    VectorAssembler,
 };
 
 #[test]
@@ -134,29 +134,6 @@ fn transformer_and_model_accessors() {
     let _ = VectorAssembler::default();
 
     // Models with public fields: construct directly and exercise Transformer 
+ Model methods.
-    let mut m = StringIndexerModel {
-        operator: MlOperator::new("si", OperatorType::Model),
-        params: Params::new(),
-        input_col: "a".to_string(),
-        output_col: "b".to_string(),
-    };
-    let _ = m.operator();
-    let _ = m.operator_mut();
-    let _ = m.params();
-    let _ = m.params_mut();
-    let _ = m.clone_box();
-
-    let mut m = MaxAbsScalerModel {
-        operator: MlOperator::new("ma", OperatorType::Model),
-        params: Params::new(),
-        input_col: "a".to_string(),
-        output_col: "b".to_string(),
-    };
-    let _ = m.operator();
-    let _ = m.operator_mut();
-    let _ = m.params();
-    let _ = m.params_mut();
-    let _ = m.clone_box();
 
     let mut m = PipelineModel {
         operator: MlOperator::new("pl", OperatorType::Model),
diff --git a/crates/spark-connect/tests/e2e_coverage.rs 
b/crates/spark-connect/tests/e2e_coverage.rs
index 7d486346..53c77e05 100644
--- a/crates/spark-connect/tests/e2e_coverage.rs
+++ b/crates/spark-connect/tests/e2e_coverage.rs
@@ -1204,25 +1204,30 @@ fn ml_estimators_and_transformers() {
         .set_output_col("assembled");
     let _ = va.transform(&df).and_then(|d| d.count());
 
-    // These estimator wrappers construct models locally; transform builds a 
relation.
+    // The server fits each scaler and indexer, and the transform of the model 
uses the cached
+    // model. The scalers take ML vector features.
+    let vectors = df.with_column(
+        "vfeatures",
+        
spark_connect::Column::new(spark_connect::expression::Expression::function(
+            "array_to_vector",
+            vec![col("features").expression().clone()],
+        )),
+    );
     let mut ss = StandardScaler::new()
-        .set_input_col("features")
+        .set_input_col("vfeatures")
         .set_output_col("scaled");
-    if let Ok(mut m) = ss.fit(&df) {
-        let _ = m.transform(&df).and_then(|d| d.count());
-    }
+    let mut m = ss.fit(&vectors).expect("fit StandardScaler");
+    assert_eq!(m.transform(&vectors).unwrap().count().unwrap(), 20);
     let mut mas = MaxAbsScaler::new()
-        .set_input_col("features")
+        .set_input_col("vfeatures")
         .set_output_col("maxabs");
-    if let Ok(mut m) = mas.fit(&df) {
-        let _ = m.transform(&df).and_then(|d| d.count());
-    }
+    let mut m = mas.fit(&vectors).expect("fit MaxAbsScaler");
+    assert_eq!(m.transform(&vectors).unwrap().count().unwrap(), 20);
     let mut si = StringIndexer::new()
         .set_input_col("s")
         .set_output_col("s_idx");
-    if let Ok(mut m) = si.fit(&df) {
-        let _ = m.transform(&df).and_then(|d| d.count());
-    }
+    let mut m = si.fit(&df).expect("fit StringIndexer");
+    assert_eq!(m.transform(&df).unwrap().count().unwrap(), 20);
 
     // RegressionEvaluator.evaluate now sends a real MlCommand::Evaluate and 
reads
     // the metric back (previously a stub returning 0.0). With prediction == 
label
diff --git a/crates/spark-connect/tests/ml_extra_golden.rs 
b/crates/spark-connect/tests/ml_extra_golden.rs
index f7f6d862..69f35ecf 100644
--- a/crates/spark-connect/tests/ml_extra_golden.rs
+++ b/crates/spark-connect/tests/ml_extra_golden.rs
@@ -14,8 +14,8 @@ use prost::Message;
 
 use spark_connect::ml::{
     BinaryClassificationEvaluator, Estimator, Evaluator, LogisticRegression, 
MaxAbsScaler,
-    MaxAbsScalerModel, MlOperator, OperatorType, Params, Pipeline, 
PipelineModel,
-    RegressionEvaluator, StringIndexer, StringIndexerModel, Transformer, 
VectorAssembler,
+    MlOperator, OperatorType, Params, Pipeline, PipelineModel, 
RegressionEvaluator, StringIndexer,
+    Transformer, VectorAssembler,
 };
 use spark_connect_proto as proto;
 
@@ -111,21 +111,6 @@ fn test_string_indexer_operator_name() {
     assert_eq!(op.op_type, OperatorType::Estimator);
 }
 
-#[test]
-fn test_string_indexer_model_operator_type() {
-    let model = StringIndexerModel {
-        operator: MlOperator::new(
-            "org.apache.spark.ml.feature.StringIndexer",
-            OperatorType::Model,
-        ),
-        params: Params::new(),
-        input_col: "col".to_string(),
-        output_col: "indexed".to_string(),
-    };
-    let op = model.operator();
-    assert_eq!(op.op_type, OperatorType::Model);
-}
-
 #[test]
 fn test_max_abs_scaler_operator_name() {
     let scaler = MaxAbsScaler::new();
@@ -134,21 +119,6 @@ fn test_max_abs_scaler_operator_name() {
     assert_eq!(op.op_type, OperatorType::Estimator);
 }
 
-#[test]
-fn test_max_abs_scaler_model_operator_type() {
-    let model = MaxAbsScalerModel {
-        operator: MlOperator::new(
-            "org.apache.spark.ml.feature.MaxAbsScaler",
-            OperatorType::Model,
-        ),
-        params: Params::new(),
-        input_col: "features".to_string(),
-        output_col: "scaled".to_string(),
-    };
-    let op = model.operator();
-    assert_eq!(op.op_type, OperatorType::Model);
-}
-
 #[test]
 fn test_logistic_regression_operator_name() {
     let lr = LogisticRegression::new();
diff --git a/python/pyspark/sql/connect/client/__init__.py 
b/python/pyspark/sql/connect/client/__init__.py
index 0774ad42..9bd85ce7 100644
--- a/python/pyspark/sql/connect/client/__init__.py
+++ b/python/pyspark/sql/connect/client/__init__.py
@@ -293,6 +293,31 @@ class SparkConnectClient:
         except Exception:
             pass
 
+    def _get_ml_cache_info(self) -> List[str]:
+        """The cached ML objects of the session on the server, as 
SparkConnectClient's: their
+        JSON descriptions."""
+        import pyspark.sql.connect.proto as pb2
+
+        command = pb2.Command()
+        command.ml_command.get_cache_info.SetInParent()
+        _, properties, _ = self.execute_command(command)
+        if "ml_command_result" in properties:
+            ml_command_result = properties["ml_command_result"]
+            return [item.string for item in 
ml_command_result.param.array.elements]
+        return []
+
+    def _query_model_size(self, model_ref_id: str) -> int:
+        """The size of the cached model of ``model_ref_id`` on the server, as 
SparkConnectClient's:
+        in bytes."""
+        import pyspark.sql.connect.proto as pb2
+
+        command = pb2.Command()
+        command.ml_command.get_model_size.CopyFrom(
+            
pb2.MlCommand.GetModelSize(model_ref=pb2.ObjectRef(id=model_ref_id))
+        )
+        _, properties, _ = self.execute_command(command)
+        return properties["ml_command_result"].param.long
+
 
 def _extensions_of(extensions: Any) -> List[Any]:
     # The user context extensions of the Rust transport, as SparkConnectClient 
keeps them: the
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index 12864f11..a03bf03c 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -55,6 +55,31 @@ def _labeled(session):
     return session.createDataFrame(rows, ["id", "label", "features"])
 
 
+def test_ml_connect_scalers_fit_and_transform_as_pyspark(session):
+    # pyspark.ml.connect's StandardScaler, MaxAbsScaler and StringIndexer: the 
server fits each one
+    # and caches the model, and the transform of the model gives the values of 
PySpark 4.3.0.
+    from pyspark.ml.connect.feature import MaxAbsScaler, StandardScaler, 
StringIndexer
+    from pyspark.ml.connect.functions import array_to_vector
+
+    rows = [(1, [2.0, 4.0], "a"), (2, [4.0, 2.0], "b"), (3, [6.0, 6.0], "a")]
+    df = session.createDataFrame(rows, "x int, f array<double>, s string")
+    df = df.withColumn("v", array_to_vector("f"))
+
+    def rows(frame, column):
+        return [row[column] for row in frame.orderBy("x").collect()]
+
+    scaled = StandardScaler(inputCol="v", outputCol="o").fit(df).transform(df)
+    values = [v.toArray().tolist() for v in rows(scaled, "o")]
+    assert values == [[1.0, 2.0], [2.0, 1.0], [3.0, 3.0]]
+
+    maxabs = MaxAbsScaler(inputCol="v", outputCol="o").fit(df).transform(df)
+    values = [v.toArray().tolist() for v in rows(maxabs, "o")]
+    assert values[0] == pytest.approx([1 / 3, 2 / 3]) and values[2] == [1.0, 
1.0]
+
+    indexed = StringIndexer(inputCol="s", outputCol="o").fit(df).transform(df)
+    assert rows(indexed, "o") == [0.0, 1.0, 0.0]
+
+
 def test_ml_classifiers_fit_transform_and_summarize_as_pyspark(session):
     from pyspark.ml.classification import LogisticRegression, 
LogisticRegressionModel
 
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index 657b4839..a5c79f64 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -122,6 +122,65 @@ class _Color(enum.Enum):
 _UTF8 = 'string { collation: "UTF8_BINARY" }'
 
 
+def test_ml_cache_queries_are_those_of_pyspark(ml_mock):
+    # As PySpark Connect's SparkConnectClient._get_ml_cache_info and 
_query_model_size: the
+    # get_cache_info and get_model_size commands, and the JSON of the cached 
objects, or the size
+    # of the model, of their results.
+    spark, service = ml_mock
+    client = spark.client
+    cached = [pb2.Expression.Literal(string='{"class": "a"}'), 
pb2.Expression.Literal(string="{}")]
+    service.execute_payload = _ml_result(
+        
param=pb2.Expression.Literal(array=pb2.Expression.Literal.Array(elements=cached))
+    )
+    assert client._get_ml_cache_info() == ['{"class": "a"}', "{}"]
+    (command,) = _commands(service)
+    assert command.ml_command.HasField("get_cache_info")
+
+    service.execute_payload = _operator_info("ref-1")
+    assert client._get_ml_cache_info() == []
+
+    service.execute_payload = _ml_result(param=pb2.Expression.Literal(long=42))
+    assert client._query_model_size("ref-1") == 42
+    command = _commands(service)[-1]
+    assert command.ml_command.get_model_size.model_ref == 
pb2.ObjectRef(id="ref-1")
+
+
+def test_ml_connect_fitted_scalers_transform_the_cached_model(ml_mock):
+    # As the fitted models of PySpark Connect: fit sends an MlCommand.Fit of 
the estimator, and the
+    # transform of the fitted model refers to the object that the server 
cached for the fit, not to
+    # a transformer of the estimator's name, which the server rejects.
+    from pyspark.ml.connect.feature import MaxAbsScaler, StandardScaler, 
StringIndexer
+
+    spark, service = ml_mock
+    df = spark.range(1).selectExpr("array(1.0D, 2.0D) AS f", "'a' AS s")
+    models = []  # Kept alive, so that no model is released during the checks.
+    for cls, name, column in [
+        (StandardScaler, "org.apache.spark.ml.feature.StandardScaler", "f"),
+        (MaxAbsScaler, "org.apache.spark.ml.feature.MaxAbsScaler", "f"),
+        (StringIndexer, "org.apache.spark.ml.feature.StringIndexer", "s"),
+    ]:
+        sent = len(service.execute_requests)
+        service.execute_payload = _operator_info("model-1")
+        estimator = cls(inputCol=column, outputCol="o")
+        models.append(estimator.fit(df))
+        fit = _commands(service)[sent].ml_command.fit
+        assert fit.estimator.name == name
+        assert fit.estimator.type == pb2.MlOperator.OPERATOR_TYPE_ESTIMATOR
+        assert dict(fit.params.params) == {
+            "inputCol": pb2.Expression.Literal(string=column),
+            "outputCol": pb2.Expression.Literal(string="o"),
+        }
+        assert fit.dataset == _relation(df)
+
+        scaled = models[-1].transform(df)
+        assert len(service.execute_requests) == sent + 1
+        transform = _relation(scaled).ml_relation.transform
+        assert transform.obj_ref == pb2.ObjectRef(id="model-1")
+        assert not transform.HasField("transformer")
+        assert transform.input == _relation(df)
+        assert transform.params.params["outputCol"] == 
pb2.Expression.Literal(string="o")
+
+
 @pytest.mark.parametrize(
     "value, expected",
     [


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to