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 abcfc606 [SPARK-61477][CONNECT][PYTHON] Raise NOT_IMPLEMENTED from the
native Pipeline.fit of no stages, and correct the seed and label docs of the
native tree classifiers
abcfc606 is described below
commit abcfc606d597e3dd674dd2d0927345a389e90ed9
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 09:43:50 2026 +0900
[SPARK-61477][CONNECT][PYTHON] Raise NOT_IMPLEMENTED from the native
Pipeline.fit of no stages, and correct the seed and label docs of the native
tree classifiers
### What changes were proposed in this pull request?
- The native `Pipeline.fit` and `CrossValidator.fit` of the Python client
ran the checks of PySpark's param serialization (`VALUE_NOT_BETWEEN` for an int
that cannot be sent, `CANNOT_INFER_ARRAY_ELEMENT_TYPE` for an empty list)
before the core raised `NOT_IMPLEMENTED`. They now raise `NOT_IMPLEMENTED` for
every param state, without a request.
- The docs of the native `DecisionTreeClassifier` and
`RandomForestClassifier`, in the Rust API and in `docs/compatibility.md`, now
describe the seed and the labels as Spark 4.3.0 implements them. A single tree
uses the seed only to sample the rows that find its split candidates on large
inputs, and it chooses equal-gain splits deterministically. Labels are
non-negative integer class indices below `numClasses`, so a class with no rows
is allowed.
- `e2e_random_forest_regressor.rs` uses `common::live_session` instead of
its own copy of it, the long import of `pyspark/ml/connect/__init__.py` is
wrapped, and the decision tree unit tests use `assert!` for bools.
### Why are the changes needed?
`pyspark.ml.connect.pipeline.Pipeline(stages=[]).fit(df)` raised
`PySparkTypeError` `CANNOT_INFER_ARRAY_ELEMENT_TYPE`, and a test said PySpark
does so. `Pipeline(stages=["a"]).fit(df)` raised `PySparkNotImplementedError`
`NOT_IMPLEMENTED`. PySpark's `Pipeline(stages=[]).fit` returns an empty
`PipelineModel`. The drop-in cannot fit a native pipeline at all, so it now
raises `NOT_IMPLEMENTED` in every case. `CrossValidator(seed=2**64).fit` raised
`VALUE_NOT_BETWEEN` for the same reason, [...]
The docs claimed that the seed of a decision tree breaks ties between equal
splits, and that labels must be contiguous class indices starting at zero.
Neither matches Spark 4.3.0. In `RandomForest.findSplits`, the seed samples the
input when it has more than `max(maxBins^2, 10000)` rows, and the best split is
a `maxBy` of the gains. `getNumClasses` takes the label metadata, else the
maximum label plus one. With `maxBins=4` on 30,000 rows, seeds 1 and 2 give
different predictions, and [...]
This is a follow-up of SPARK-61399 (#490), SPARK-61391 (#487) and
SPARK-61450 (#512).
### Does this PR introduce _any_ user-facing change?
Yes. `Pipeline.fit` and `CrossValidator.fit` of the native classes now
raise `NOT_IMPLEMENTED` where an empty-list or unsendable param raised
`CANNOT_INFER_ARRAY_ELEMENT_TYPE` or `VALUE_NOT_BETWEEN`. The rest is
documentation and tests.
### How was this patch tested?
`test_ml_pipeline_and_cross_validator_fit_is_not_implemented` in
`python/tests/test_ml_offline.py` now covers `Pipeline(stages=[])`,
`CrossValidator(seed=2**64)` and `CrossValidator(numFolds=2**70)`. It asserts
`NOT_IMPLEMENTED` and that no request is sent, and fails without this change.
The ML offline suite (110 passed), the drop-in offline suite, the Rust library
tests, the `--no-run` builds (with and without `wasm-udf`), and the Rust and
Python ML e2e suites against Spark 4.3.0 pas [...]
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5
This pull request and its description were written by Isaac.
Closes #530 from HyukjinKwon/SPARK-61477-native-ml.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/ml.rs | 28 ++++++++++++++++++----
crates/spark-connect/src/ml.rs | 24 +++++++++++--------
.../tests/e2e_random_forest_regressor.rs | 21 ++++++----------
docs/compatibility.md | 8 +++----
python/pyspark/ml/connect/__init__.py | 7 +++++-
python/tests/test_ml_offline.py | 14 +++++++----
6 files changed, 64 insertions(+), 38 deletions(-)
diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index 8ec25534..8830b662 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -259,9 +259,29 @@ where
T: Native + PyClass,
T::Core: Estimator,
{
- let mut estimator = snapshot(slf)?;
+ let estimator = snapshot(slf)?;
+ fit_core(slf.py(), estimator, df)
+}
+
+/// The fit of a native estimator whose core cannot fit it, as Pipeline and
CrossValidator.
+/// The core raises NOT_IMPLEMENTED before any request, whatever its params
are, so the params
+/// are not serialized first, and PySpark's serialization errors of them are
not raised.
+fn fit_unimplemented<T>(slf: &Bound<'_, T>, df: &PyDataFrame) ->
PyResult<PyMLModel>
+where
+ T: Native + PyClass,
+ T::Core: Estimator,
+{
+ let estimator = slf.try_borrow()?.inner().clone();
+ fit_core(slf.py(), estimator, df)
+}
+
+fn fit_core<C: Estimator>(
+ py: Python<'_>,
+ mut estimator: C,
+ df: &PyDataFrame,
+) -> PyResult<PyMLModel> {
let session = df.dataframe.spark_session();
- let model = interruptible(slf.py(), &session, || {
+ let model = interruptible(py, &session, || {
estimator.fit(&df.dataframe).map_err(Box::new)
})?;
Ok(PyMLModel {
@@ -1805,7 +1825,7 @@ impl PyPipeline {
set_param(slf, "stages", Kind::StrList, value)
}
fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
- fit_native(slf, df)
+ fit_unimplemented(slf, df)
}
}
@@ -1931,7 +1951,7 @@ impl PyCrossValidator {
set_param(slf, "seed", Kind::Int, value)
}
fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
- fit_native(slf, df)
+ fit_unimplemented(slf, df)
}
}
diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index b94689cd..9b663d15 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -1876,9 +1876,11 @@ impl Model for LinearRegressionModel {
/// Decision tree classification using Spark's JVM implementation and ML
vector features.
///
-/// Supports binary and multiclass labels. Unset parameters use Spark's
defaults. Without a
-/// seed, tie-breaking uses Spark's default seed (the hash of the class name),
as with
-/// PySpark, so fits are reproducible either way; set a seed to change
tie-breaking.
+/// Supports binary and multiclass labels. Unset parameters use Spark's
defaults. A single
+/// tree samples its rows to find split candidates only when there are more
than
+/// max(maxBins^2, 10000) rows; the seed picks that sample, or else Spark's
default seed (the
+/// hash of the class name), as with PySpark, so fits are reproducible either
way. Equal-gain
+/// splits are chosen deterministically, so the seed does not break ties.
#[derive(Debug, Clone)]
pub struct DecisionTreeClassifier {
operator: MlOperator,
@@ -1902,7 +1904,8 @@ impl DecisionTreeClassifier {
self
}
- /// Numeric label column; labels must be contiguous class indices starting
at zero.
+ /// Numeric label column of non-negative integer class indices below
numClasses, which
+ /// is the label column metadata's count, else the maximum label plus one.
pub fn set_label_col(mut self, value: &str) -> Self {
self.params = self.params.set_param_string("labelCol", value);
self
@@ -1980,7 +1983,7 @@ impl DecisionTreeClassifier {
self
}
- /// Random seed for breaking ties between equally good splits.
+ /// Random seed for sampling the rows that find the split candidates, on
large inputs.
pub fn set_seed(mut self, value: i64) -> Self {
self.params = self.params.set_param_int_narrow("seed", value);
self
@@ -2223,7 +2226,8 @@ impl RandomForestClassifier {
self
}
- /// Numeric label column; labels must be contiguous class indices starting
at zero.
+ /// Numeric label column of non-negative integer class indices below
numClasses, which
+ /// is the label column metadata's count, else the maximum label plus one.
pub fn set_label_col(mut self, value: &str) -> Self {
self.params = self.params.set_param_string("labelCol", value);
self
@@ -4411,9 +4415,9 @@ mod tests {
assert_eq!(tree.max_bins(), 32);
assert_eq!(tree.min_instances_per_node(), 1);
assert_eq!(tree.min_info_gain(), 0.0);
- assert_eq!(tree.prune_tree(), true);
+ assert!(tree.prune_tree());
assert_eq!(tree.max_memory_in_mb(), 256);
- assert_eq!(tree.cache_node_ids(), false);
+ assert!(!tree.cache_node_ids());
assert_eq!(tree.checkpoint_interval(), 10);
assert_eq!(tree.impurity(), "gini");
assert_eq!(tree.seed(), None);
@@ -4487,13 +4491,13 @@ mod tests {
assert_eq!(tree.min_info_gain(), 0.01);
assert_eq!(built.min_info_gain(), tree.min_info_gain());
*tree.params_mut() = tree.params().clone().set_param_bool("pruneTree",
false);
- assert_eq!(tree.prune_tree(), false);
+ assert!(!tree.prune_tree());
assert_eq!(built.prune_tree(), tree.prune_tree());
*tree.params_mut() =
tree.params().clone().set_param_int32("maxMemoryInMB", 64);
assert_eq!(tree.max_memory_in_mb(), 64);
assert_eq!(built.max_memory_in_mb(), tree.max_memory_in_mb());
*tree.params_mut() =
tree.params().clone().set_param_bool("cacheNodeIds", true);
- assert_eq!(tree.cache_node_ids(), true);
+ assert!(tree.cache_node_ids());
assert_eq!(built.cache_node_ids(), tree.cache_node_ids());
*tree.params_mut() = tree
.params()
diff --git a/crates/spark-connect/tests/e2e_random_forest_regressor.rs
b/crates/spark-connect/tests/e2e_random_forest_regressor.rs
index 8fa407c2..2fa80244 100644
--- a/crates/spark-connect/tests/e2e_random_forest_regressor.rs
+++ b/crates/spark-connect/tests/e2e_random_forest_regressor.rs
@@ -1,19 +1,12 @@
//! Native random forest regression tests. Set SPARK_REMOTE to run against a
live Connect server.
+mod common;
+
+use common::live_session;
use spark_connect::column::{col, lit_double, lit_string};
use spark_connect::expression::Expression;
use spark_connect::ml::{Estimator, RandomForestRegressor};
use spark_connect::{Column, DataFrame, SparkSession};
-fn session() -> Option<SparkSession> {
- let remote = std::env::var("SPARK_REMOTE").ok()?;
- Some(
- SparkSession::builder()
- .remote(&remote)
- .get_or_create()
- .unwrap(),
- )
-}
-
fn vectors(s: &SparkSession, sql: &str, name: &str) -> DataFrame {
s.sql(sql).unwrap().with_column(
name,
@@ -54,7 +47,7 @@ fn deterministic() -> RandomForestRegressor {
#[test]
fn
random_forest_regressor_learns_nonlinear_labels_and_keeps_cached_models_alive()
{
- let Some(s) = session() else {
+ let Some(s) = live_session() else {
return;
};
let training = vectors(
@@ -140,7 +133,7 @@ fn
random_forest_regressor_learns_nonlinear_labels_and_keeps_cached_models_alive
#[test]
fn random_forest_regressor_weights_change_the_predicted_mean() {
- let Some(s) = session() else {
+ let Some(s) = live_session() else {
return;
};
let data = vectors(
@@ -168,7 +161,7 @@ fn
random_forest_regressor_weights_change_the_predicted_mean() {
#[test]
fn random_forest_regressor_bootstrap_sampling_is_reproducible() {
- let Some(s) = session() else {
+ let Some(s) = live_session() else {
return;
};
let data = vectors(
@@ -200,7 +193,7 @@ fn
random_forest_regressor_bootstrap_sampling_is_reproducible() {
#[test]
fn random_forest_regressor_rejects_invalid_parameters_and_data() {
- let Some(s) = session() else {
+ let Some(s) = live_session() else {
return;
};
let data = vectors(
diff --git a/docs/compatibility.md b/docs/compatibility.md
index a87a8e06..fe4ed992 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -212,8 +212,8 @@ not exposed by this native addition.
## Native DecisionTreeClassifier
`spark_connect::ml::DecisionTreeClassifier` trains Spark's JVM decision tree
-classifier through Connect with ML vector features and contiguous numeric class
-labels starting at zero. Rust builder setters cover all 18 PySpark constructor
+classifier through Connect with ML vector features and non-negative integer
class
+labels below numClasses. Rust builder setters cover all 18 PySpark constructor
parameters, including `pruneTree` (Spark 4.3.0), plus class thresholds. Unset
parameters use Spark's defaults.
@@ -232,8 +232,8 @@ importances, single-vector prediction and persistence are
outside this addition.
## Native RandomForestClassifier
`spark_connect::ml::RandomForestClassifier` trains Spark's JVM random forest
-classifier through Connect with ML vector features and contiguous numeric class
-labels starting at zero. Rust builder setters cover all 22 PySpark constructor
+classifier through Connect with ML vector features and non-negative integer
class
+labels below numClasses. Rust builder setters cover all 22 PySpark constructor
parameters, including `pruneTree` (Spark 4.3.0), plus class thresholds. Unset
parameters use Spark's defaults. Without a seed, the sampling uses Spark's
default
seed (the hash of the class name), as with PySpark, so fits are reproducible
either
diff --git a/python/pyspark/ml/connect/__init__.py
b/python/pyspark/ml/connect/__init__.py
index f13a5d6c..0d662273 100644
--- a/python/pyspark/ml/connect/__init__.py
+++ b/python/pyspark/ml/connect/__init__.py
@@ -11,7 +11,12 @@ from pyspark.ml.connect.feature import (
StringIndexer,
VectorAssembler,
)
-from pyspark.ml.connect.classification import DecisionTreeClassifier,
LinearSVC, LogisticRegression, RandomForestClassifier
+from pyspark.ml.connect.classification import (
+ DecisionTreeClassifier,
+ LinearSVC,
+ LogisticRegression,
+ RandomForestClassifier,
+)
from pyspark.ml.connect.regression import LinearRegression,
RandomForestRegressor
from pyspark.ml.connect.clustering import KMeans
from pyspark.ml.connect.evaluation import (
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index 859489ba..7f16a692 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -301,6 +301,12 @@ def
test_ml_pipeline_and_cross_validator_fit_is_not_implemented(ml_mock):
(cv, "CrossValidator.fit"),
(Pipeline(stages=["a"]), "Pipeline.fit"),
(CrossValidator(numFolds=2, seed=1), "CrossValidator.fit"),
+ # The params that PySpark's serialization cannot send, or sends as an
empty list, do not
+ # raise their errors first: the fit raises NOT_IMPLEMENTED for every
param state.
+ (Pipeline(stages=[]), "Pipeline.fit"),
+ (CrossValidator(seed=2**64), "CrossValidator.fit"),
+ (CrossValidator(seed=2**64, numFolds=2), "CrossValidator.fit"),
+ (CrossValidator(numFolds=2**70), "CrossValidator.fit"),
]:
sent = _requests_but_deletes(service)
with pytest.raises(PySparkNotImplementedError) as error:
@@ -568,7 +574,9 @@ def
test_ml_connect_evaluators_take_the_signatures_and_defaults_of_pyspark(ml_mo
def test_ml_connect_unsendable_ints_none_and_uids_as_pyspark(ml_mock):
# As PySpark: an int beyond a long is taken by the constructor and the
setter, and the
# next fit raises the VALUE_NOT_BETWEEN of PySpark's serialization of the
params, before
- # any request, until the param is set again. None is sent as a null, as
PySpark sends it.
+ # any request, until the param is set again. A CrossValidator raises
NOT_IMPLEMENTED instead,
+ # see test_ml_pipeline_and_cross_validator_fit_is_not_implemented. None is
sent as a null,
+ # as PySpark sends it.
# The uid of every native class is the name of its class and 12 hex
digits, as PySpark's.
import re
@@ -580,7 +588,6 @@ def
test_ml_connect_unsendable_ints_none_and_uids_as_pyspark(ml_mock):
connect.KMeans(seed=2**64),
connect.KMeans().setSeed(-(2**63) - 1),
connect.RandomForestClassifier().setNumTrees(2**70),
- connect.CrossValidator(numFolds=2**70),
]:
sent = _requests_but_deletes(service)
with pytest.raises(PySparkValueError) as error:
@@ -2344,7 +2351,6 @@ def
test_ml_none_params_send_null_and_empty_lists_raise_at_the_command_as_pyspar
# setters, and PySpark raises CANNOT_INFER_ARRAY_ELEMENT_TYPE when its
serialization sends
# the params of a fit, transform or evaluate, before any request.
import pyspark.ml.connect as connect
- from pyspark.ml.connect.pipeline import Pipeline
spark, service = ml_mock
df = spark.range(1)
@@ -2363,8 +2369,6 @@ def
test_ml_none_params_send_null_and_empty_lists_raise_at_the_command_as_pyspar
assert error.value.getCondition() == "CANNOT_INFER_ARRAY_ELEMENT_TYPE"
with pytest.raises(PySparkTypeError,
match="CANNOT_INFER_ARRAY_ELEMENT_TYPE"):
connect.RandomForestClassifier().setThresholds([]).fit(df)
- with pytest.raises(PySparkTypeError,
match="CANNOT_INFER_ARRAY_ELEMENT_TYPE"):
- Pipeline(stages=[]).fit(df)
assert len(service.execute_requests) == before
# Elements given again make the list sendable.
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]