You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "WeichenXu123 (via GitHub)" <gi...@apache.org> on 2023/06/06 12:32:49 UTC

[GitHub] [spark] WeichenXu123 opened a new pull request, #41478: [WIP][SPARK-43981][PYTHON][ML] Basic saving / loading implementation for ML on spark connect

WeichenXu123 opened a new pull request, #41478:
URL: https://github.com/apache/spark/pull/41478

   <!--
   Thanks for sending a pull request!  Here are some tips for you:
     1. If this is your first time, please read our contributor guidelines: https://spark.apache.org/contributing.html
     2. Ensure you have added or run the appropriate tests for your PR: https://spark.apache.org/developer-tools.html
     3. If the PR is unfinished, add '[WIP]' in your PR title, e.g., '[WIP][SPARK-XXXX] Your PR title ...'.
     4. Be sure to keep the PR description updated to reflect all changes.
     5. Please write your PR title to summarize what this PR proposes.
     6. If possible, provide a concise example to reproduce the issue for a faster review.
     7. If you want to add a new configuration, please read the guideline first for naming configurations in
        'core/src/main/scala/org/apache/spark/internal/config/ConfigEntry.scala'.
     8. If you want to add or modify an error type or message, please read the guideline first in
        'core/src/main/resources/error/README.md'.
   -->
   
   ### What changes were proposed in this pull request?
   <!--
   Please clarify what changes you are proposing. The purpose of this section is to outline the changes and how this PR fixes the issue. 
   If possible, please consider writing useful notes for better and faster reviews in your PR. See the examples below.
     1. If you refactor some codes with changing classes, showing the class hierarchy will help reviewers.
     2. If you fix some SQL features, you can provide some references of other DBMSes.
     3. If there is design documentation, please add the link.
     4. If there is a discussion in the mailing list, please add the link.
   -->
   
   
   ### Why are the changes needed?
   <!--
   Please clarify why the changes are needed. For instance,
     1. If you propose a new API, clarify the use case for a new API.
     2. If you fix a bug, you can clarify why it is a bug.
   -->
   
   
   ### Does this PR introduce _any_ user-facing change?
   <!--
   Note that it means *any* user-facing change including all aspects such as the documentation fix.
   If yes, please clarify the previous behavior and the change this PR proposes - provide the console output, description and/or an example to show the behavior difference if possible.
   If possible, please also clarify if this is a user-facing change compared to the released Spark versions or within the unreleased branches such as master.
   If no, write 'No'.
   -->
   
   
   ### How was this patch tested?
   <!--
   If tests were added, say they were added here. Please make sure to add some test cases that check the changes thoroughly including negative and positive cases if possible.
   If it was tested in a way different from regular unit tests, please clarify how you tested step by step, ideally copy and paste-able, so that other reviewers can test and check, and descendants can verify in the future.
   If tests were not added, please describe why they were not added and/or why it was difficult to add.
   If benchmark tests were added, please run the benchmarks in GitHub Actions for the consistent environment, and the instructions could accord to: https://spark.apache.org/developer-tools.html#github-workflow-benchmarks.
   -->
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] WeichenXu123 commented on a diff in pull request #41478: [WIP][SPARK-43981][PYTHON][ML] Basic saving / loading implementation for ML on spark connect

Posted by "WeichenXu123 (via GitHub)" <gi...@apache.org>.
WeichenXu123 commented on code in PR #41478:
URL: https://github.com/apache/spark/pull/41478#discussion_r1222997971


##########
python/pyspark/mlv2/io_utils.py:
##########
@@ -0,0 +1,159 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import json
+import os
+import time
+from typing import Any, Dict, Optional
+from pyspark.errors import PySparkNotImplementedError, PySparkRuntimeError
+from pyspark.util import VersionUtils
+
+from pyspark import __version__ as pyspark_version

Review Comment:
   For new pyspark ML module, I think we should regard it as a client side package so using client side pyspark version should be fine. Pyspark server side just runs wrapped python UDF which is unaware of concrete ML algorithm logic.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] WeichenXu123 closed pull request #41478: [SPARK-43981][PYTHON][ML] Basic saving / loading implementation for ML on spark connect

Posted by "WeichenXu123 (via GitHub)" <gi...@apache.org>.
WeichenXu123 closed pull request #41478: [SPARK-43981][PYTHON][ML] Basic saving / loading implementation for ML on spark connect
URL: https://github.com/apache/spark/pull/41478


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] WeichenXu123 commented on a diff in pull request #41478: [WIP][SPARK-43981][PYTHON][ML] Basic saving / loading implementation for ML on spark connect

Posted by "WeichenXu123 (via GitHub)" <gi...@apache.org>.
WeichenXu123 commented on code in PR #41478:
URL: https://github.com/apache/spark/pull/41478#discussion_r1228182306


##########
python/pyspark/mlv2/io_utils.py:
##########
@@ -0,0 +1,159 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import json
+import os
+import time
+from typing import Any, Dict, Optional
+from pyspark.errors import PySparkNotImplementedError, PySparkRuntimeError
+from pyspark.util import VersionUtils
+
+from pyspark import __version__ as pyspark_version
+
+
+_META_DATA_FILE_NAME = "metadata.json"
+
+
+def _get_metadata_to_save(
+        instance: "Params",
+        extra_metadata: Optional[Dict[str, Any]] = None,
+) -> str:
+    """
+    Extract metadata of Estimator / Transformer / Model / Evaluator instance.
+    """
+    uid = instance.uid
+    cls = instance.__module__ + "." + instance.__class__.__name__
+
+    # User-supplied param values
+    params = instance._paramMap
+    json_params = {}
+    for p in params:
+        json_params[p.name] = params[p]
+
+    # Default param values
+    json_default_params = {}
+    for p in instance._defaultParamMap:
+        json_default_params[p.name] = instance.json_default_params[p]
+
+    metadata = {
+        "class": cls,
+        "timestamp": int(round(time.time() * 1000)),
+        "sparkVersion": pyspark_version,
+        "uid": uid,
+        "paramMap": json_params,
+        "defaultParamMap": json_default_params,
+        "type": "spark_connect",
+    }
+    if extra_metadata is not None:
+        metadata.update(extra_metadata)
+
+    return metadata
+
+
+def _get_class(clazz: str) -> Any:
+    """
+    Loads Python class from its name.
+    """
+    parts = clazz.split(".")
+    module = ".".join(parts[:-1])
+    m = __import__(module, fromlist=[parts[-1]])
+    return getattr(m, parts[-1])
+
+
+class ParamsReadWrite:
+    """
+    The base interface Estimator / Transformer / Model / Evaluator needs to inherit
+    for supporting saving and loading.
+    """
+
+    def _get_metadata(self) -> Any:
+        """
+        Returns metadata of the object as a JSON object.
+        """
+        return _get_metadata_to_save(self)
+
+    # TODO: support saving to cloud storage file system.
+    def saveToLocal(self, path):
+        """
+        Save model to provided local path.
+        """
+        metadata = self._get_metadata()
+
+        os.makedirs(path)
+        with open(os.path.join(path, _META_DATA_FILE_NAME), "w") as fp:
+            json.dump(metadata, fp)
+
+    # TODO: support loading from cloud storage file system.
+    @classmethod
+    def loadFromLocal(cls, path):
+        """
+        Load model from provided local path.
+        """
+        with open(os.path.join(path, _META_DATA_FILE_NAME), "r") as fp:
+            metadata = json.load(fp)
+
+        if "type" not in metadata or metadata["type"] != "spark_connect":
+            raise RuntimeError("The model is not saved by spark ML under spark connect mode.")
+
+        class_name = metadata["class"]
+        instance = _get_class(class_name)()
+        instance._resetUid(metadata["uid"])
+
+        # Set user-supplied param values
+        for paramName in metadata["paramMap"]:
+            param = instance.getParam(paramName)
+            paramValue = metadata["paramMap"][paramName]
+            instance.set(param, paramValue)
+
+        for paramName in metadata["defaultParamMap"]:
+            paramValue = metadata["defaultParamMap"][paramName]
+            instance._setDefault(**{paramName: paramValue})
+
+        return instance
+
+
+class ModelReadWrite:

Review Comment:
   See my latest code, "ModelReadWrite" inherits from "ParamsReadWrite"



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] zhengruifeng commented on a diff in pull request #41478: [WIP][SPARK-43981][PYTHON][ML] Basic saving / loading implementation for ML on spark connect

Posted by "zhengruifeng (via GitHub)" <gi...@apache.org>.
zhengruifeng commented on code in PR #41478:
URL: https://github.com/apache/spark/pull/41478#discussion_r1222390649


##########
python/pyspark/mlv2/io_utils.py:
##########
@@ -0,0 +1,159 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import json
+import os
+import time
+from typing import Any, Dict, Optional
+from pyspark.errors import PySparkNotImplementedError, PySparkRuntimeError
+from pyspark.util import VersionUtils
+
+from pyspark import __version__ as pyspark_version

Review Comment:
   on python client, this version info may be different with the one `spark.version` from the sever side



##########
python/pyspark/mlv2/io_utils.py:
##########
@@ -0,0 +1,159 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import json
+import os
+import time
+from typing import Any, Dict, Optional
+from pyspark.errors import PySparkNotImplementedError, PySparkRuntimeError
+from pyspark.util import VersionUtils
+
+from pyspark import __version__ as pyspark_version
+
+
+_META_DATA_FILE_NAME = "metadata.json"
+
+
+def _get_metadata_to_save(
+        instance: "Params",
+        extra_metadata: Optional[Dict[str, Any]] = None,
+) -> str:
+    """
+    Extract metadata of Estimator / Transformer / Model / Evaluator instance.
+    """
+    uid = instance.uid
+    cls = instance.__module__ + "." + instance.__class__.__name__
+
+    # User-supplied param values
+    params = instance._paramMap
+    json_params = {}
+    for p in params:
+        json_params[p.name] = params[p]
+
+    # Default param values
+    json_default_params = {}
+    for p in instance._defaultParamMap:
+        json_default_params[p.name] = instance.json_default_params[p]
+
+    metadata = {
+        "class": cls,
+        "timestamp": int(round(time.time() * 1000)),
+        "sparkVersion": pyspark_version,
+        "uid": uid,
+        "paramMap": json_params,
+        "defaultParamMap": json_default_params,
+        "type": "spark_connect",
+    }
+    if extra_metadata is not None:
+        metadata.update(extra_metadata)
+
+    return metadata
+
+
+def _get_class(clazz: str) -> Any:
+    """
+    Loads Python class from its name.
+    """
+    parts = clazz.split(".")
+    module = ".".join(parts[:-1])
+    m = __import__(module, fromlist=[parts[-1]])
+    return getattr(m, parts[-1])
+
+
+class ParamsReadWrite:
+    """
+    The base interface Estimator / Transformer / Model / Evaluator needs to inherit
+    for supporting saving and loading.
+    """
+
+    def _get_metadata(self) -> Any:
+        """
+        Returns metadata of the object as a JSON object.
+        """
+        return _get_metadata_to_save(self)
+
+    # TODO: support saving to cloud storage file system.
+    def saveToLocal(self, path):
+        """
+        Save model to provided local path.
+        """
+        metadata = self._get_metadata()
+
+        os.makedirs(path)
+        with open(os.path.join(path, _META_DATA_FILE_NAME), "w") as fp:
+            json.dump(metadata, fp)
+
+    # TODO: support loading from cloud storage file system.
+    @classmethod
+    def loadFromLocal(cls, path):
+        """
+        Load model from provided local path.
+        """
+        with open(os.path.join(path, _META_DATA_FILE_NAME), "r") as fp:
+            metadata = json.load(fp)
+
+        if "type" not in metadata or metadata["type"] != "spark_connect":
+            raise RuntimeError("The model is not saved by spark ML under spark connect mode.")
+
+        class_name = metadata["class"]
+        instance = _get_class(class_name)()
+        instance._resetUid(metadata["uid"])
+
+        # Set user-supplied param values
+        for paramName in metadata["paramMap"]:
+            param = instance.getParam(paramName)
+            paramValue = metadata["paramMap"][paramName]
+            instance.set(param, paramValue)
+
+        for paramName in metadata["defaultParamMap"]:
+            paramValue = metadata["defaultParamMap"][paramName]
+            instance._setDefault(**{paramName: paramValue})
+
+        return instance
+
+
+class ModelReadWrite:

Review Comment:
   `ModelReadWrite` will not deal with the parameters?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org