Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SPARK-51711][ML][PYTHON][CONNECT] Propagates the active remote spark session to new threads to fix CrossValidator #50507

Open
wants to merge 16 commits into
base: master
Choose a base branch
from

Conversation

xi-db
Copy link
Contributor

@xi-db xi-db commented Apr 3, 2025

What changes were proposed in this pull request?

In SparkML with Spark Connect, the _parallelFitTasks fails when running CrossValidator fitting, as the active remote spark session is not properly propagated to the new threads.

Before the PR, this code will fail in the line cvModel = cv.fit(data):

from pyspark.ml.classification import RandomForestClassifier
from pyspark.ml.evaluation import BinaryClassificationEvaluator
from pyspark.ml.tuning import ParamGridBuilder, CrossValidator
from pyspark.ml.linalg import Vectors

data = spark.createDataFrame([
    (Vectors.dense(1.0, 2.0), 0),
    (Vectors.dense(2.0, 3.0), 1),
    (Vectors.dense(1.5, 2.5), 0),
    (Vectors.dense(3.0, 4.0), 1),
    (Vectors.dense(1.1, 2.1), 0),
    (Vectors.dense(2.5, 3.5), 1),
], ["features", "label"])

rf = RandomForestClassifier(labelCol="label", featuresCol="features")
evaluator = BinaryClassificationEvaluator(labelCol="label")
paramGrid = (ParamGridBuilder()
             .addGrid(rf.maxDepth, [2])
             .addGrid(rf.numTrees, [5, 10])
             .build())

cv = CrossValidator(estimator=rf,
                    estimatorParamMaps=paramGrid,
                    evaluator=evaluator,
                    numFolds=3)

cvModel = cv.fit(data)

bestModel = cvModel.bestModel
print(f"Best maxDepth: {bestModel.getMaxDepth()}")
print(f"Best maxBins: {bestModel.getMaxBins()}")
print(f"Best numTrees: {bestModel.getNumTrees}")

It fails because the active remote spark session is not properly set on that thread:

File ~/spark/python/pyspark/ml/util.py:250, in try_remote_call.<locals>.wrapped(self, name, *args)
    247 from pyspark.ml.connect.serialize import serialize, deserialize
    249 session = SparkSession.getActiveSession()
--> 250 assert session is not None
    251 assert isinstance(self._java_obj, str)
    252 methods, obj_ref = _extract_id_methods(self._java_obj)

AssertionError: 

With this fix, the above code snippet works correctly.

Why are the changes needed?

It fixes a bug with CrossValidator fitting.

Does this PR introduce any user-facing change?

No.

How was this patch tested?

New test.

Was this patch authored or co-authored using generative AI tooling?

No.

@xi-db xi-db changed the title Propagates the active remote spark session to new threads to fix parallelFitTasks [SPARK-51711] Propagates the active remote spark session to new threads to fix parallelFitTasks Apr 3, 2025
@xi-db xi-db changed the title [SPARK-51711] Propagates the active remote spark session to new threads to fix parallelFitTasks [SPARK-51711] Propagates the active remote spark session to new threads to fix CrossValidator Apr 3, 2025
@xi-db xi-db changed the title [SPARK-51711] Propagates the active remote spark session to new threads to fix CrossValidator [SPARK-51711][ML][PYTHON][CONNECT] Propagates the active remote spark session to new threads to fix CrossValidator Apr 3, 2025
@xi-db
Copy link
Contributor Author

xi-db commented Apr 3, 2025

Hi @zhengruifeng , could you review this PR?

It fixes a bug in SparkML via SparkConnect. The bug is reproducible with the code example in the PR description.

Thanks!

Copy link
Contributor

@WeichenXu123 WeichenXu123 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@github-actions github-actions bot removed the CONNECT label Apr 3, 2025
Copy link
Contributor

@WeichenXu123 WeichenXu123 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@github-actions github-actions bot added the SQL label Apr 4, 2025
@@ -434,7 +434,7 @@ def _fit(self, dataset: Union[pd.DataFrame, DataFrame]) -> "CrossValidatorModel"

tasks = _parallelFitTasks(est, train, eva, validation, epm)
if not is_remote():
tasks = list(map(inheritable_thread_target, tasks))
tasks = list(map(inheritable_thread_target(dataset.sparkSession), tasks))
Copy link
Contributor

@zhengruifeng zhengruifeng Apr 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this necessary?
it is under if not is_remote() branch

@@ -86,7 +86,7 @@ private[connect] class MLCache extends Logging {

private[connect] object MLCache {
// The maximum number of distinct items in the cache.
private val MAX_CACHED_ITEMS = 100
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this related?
if no, I think we should file a separate PR to increase the value

@github-actions github-actions bot removed the SQL label Apr 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants