You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "lu-wang-dl (via GitHub)" <gi...@apache.org> on 2023/07/10 22:05:02 UTC

[GitHub] [spark] lu-wang-dl commented on a diff in pull request #41770: [Spark Ticket For This Component Here] Write a Deepspeed Distributed Learning Class DeepspeedTorchDistributor

lu-wang-dl commented on code in PR #41770:
URL: https://github.com/apache/spark/pull/41770#discussion_r1258950519


##########
python/pyspark/ml/torch/deepspeed/deepspeed_distributor.py:
##########
@@ -0,0 +1,143 @@
+#
+# 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 sys
+import tempfile
+from typing import (
+    Union,
+    Callable,
+    List,
+    Dict,
+    Optional,
+    Any,
+    Tuple,
+)
+
+from pyspark.ml.torch.distributor import TorchDistributor
+
+
+class DeepspeedTorchDistributor(TorchDistributor):
+    def __init__(
+        self,
+        num_gpus: int = 1,
+        nnodes: int = 1,
+        local_mode: bool = True,
+        use_gpu: bool = True,
+        deepspeed_config=None,
+    ):

Review Comment:
   ```suggestion
       ) -> str:
   ```



##########
python/pyspark/ml/torch/deepspeed/deepspeed_distributor.py:
##########
@@ -0,0 +1,143 @@
+#
+# 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 sys
+import tempfile
+from typing import (
+    Union,
+    Callable,
+    List,
+    Dict,
+    Optional,
+    Any,
+    Tuple,
+)
+
+from pyspark.ml.torch.distributor import TorchDistributor
+
+
+class DeepspeedTorchDistributor(TorchDistributor):
+    def __init__(
+        self,
+        num_gpus: int = 1,
+        nnodes: int = 1,
+        local_mode: bool = True,
+        use_gpu: bool = True,
+        deepspeed_config=None,

Review Comment:
   ```suggestion
           deepspeed_config: Optional[Union[Dict[str,Any], str]] = None,
   ```



##########
python/pyspark/ml/torch/distributor.py:
##########
@@ -155,10 +155,7 @@ class Distributor:
     """
 
     def __init__(
-        self,
-        num_processes: int = 1,
-        local_mode: bool = True,
-        use_gpu: bool = True,
+        self, num_processes: int = 1, local_mode: bool = True, use_gpu: bool = True, ssl_conf=None

Review Comment:
   Add a type hint for `ssl_conf`?



##########
python/pyspark/ml/torch/deepspeed/deepspeed_distributor.py:
##########
@@ -0,0 +1,143 @@
+#
+# 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 sys
+import tempfile
+from typing import (
+    Union,
+    Callable,
+    List,
+    Dict,
+    Optional,
+    Any,
+    Tuple,
+)
+
+from pyspark.ml.torch.distributor import TorchDistributor
+
+
+class DeepspeedTorchDistributor(TorchDistributor):
+    def __init__(
+        self,
+        num_gpus: int = 1,
+        nnodes: int = 1,
+        local_mode: bool = True,
+        use_gpu: bool = True,
+        deepspeed_config=None,
+    ):
+        """
+        This class is used to run deepspeed training workloads with spark clusters. The user has the option to
+        specify the number of gpus per node and the number of nodes (the same as if running from terminal),
+        as well as specify a deepspeed configuration file.
+
+        Parameters
+        ----------
+        num_gpus: int
+            The number of GPUs to use per node (analagous to num_gpus in deepspeed command).
+
+        nnodes: int
+            The number of nodes that should be used for the run.
+
+        local_mode: bool
+            Whether or not to run the training in a distributed fashion or just locally.
+
+        use_gpu: bool
+            Boolean flag to determine whether to utilize gpus.
+
+        deepspeed_config: Union[Dict[str,Any], str] or None:
+            The configuration file to be used for launching the deepspeed application.
+            If it is a dictionary mapping parameters to values, then we will create the file.
+            If None, deepspeed will fall back to default parameters.
+        """
+        num_processes = num_gpus * nnodes
+        DEEPSPEED_SSL_CONF = "deepspeed.spark.distributor.ignoreSsl"
+        self.deepspeed_config = deepspeed_config
+        super().__init__(num_processes, local_mode, use_gpu, _ssl_conf=DEEPSPEED_SSL_CONF)
+        self.cleanup_deepspeed_conf = False
+
+    @staticmethod
+    def _get_deepspeed_config_path(deepspeed_config):
+        if isinstance(deepspeed_config, dict):
+            with tempfile.NamedTemporaryFile(mode="w+", delete=False, suffix=".json") as file:
+                json.dump(deepspeed_config, file)
+                return file.name
+        deepspeed_config_path = deepspeed_config
+        # Empty value means the deepspeed will fall back to default settings.
+        if deepspeed_config == None:
+            return ""
+        return deepspeed_config_path
+
+    @staticmethod
+    def _create_torchrun_command(
+        input_params: Dict[str, Any], train_path: str, *args: Any
+    ) -> List[str]:
+        local_mode = input_params["local_mode"]
+        num_processes = input_params["num_processes"]
+        deepspeed_config = input_params["deepspeed_config"]
+        deepspeed_config_path = DeepspeedTorchDistributor._get_deepspeed_config_path(
+            deepspeed_config
+        )
+        torchrun_args, processes_per_node = TorchDistributor._get_torchrun_args(
+            local_mode, num_processes
+        )
+        args_string = list(map(str, args))
+        command_to_run = [
+            sys.executable,
+            "-m",
+            "torch.distributed.run",
+            *torchrun_args,
+            f"--nproc_per_node={processes_per_node}",
+            train_path,
+            *args_string,
+            "-deepspeed",
+            "--deepspeed_config",
+            deepspeed_config_path,

Review Comment:
   Will it cause issue if `deepspeed_config_path=""`? Your command likes like
   ```
   python ...  --deepspeed_config
   ```



##########
python/pyspark/ml/torch/deepspeed/deepspeed_distributor.py:
##########
@@ -0,0 +1,143 @@
+#
+# 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 sys
+import tempfile
+from typing import (
+    Union,
+    Callable,
+    List,
+    Dict,
+    Optional,
+    Any,
+    Tuple,
+)
+
+from pyspark.ml.torch.distributor import TorchDistributor
+
+
+class DeepspeedTorchDistributor(TorchDistributor):
+    def __init__(
+        self,
+        num_gpus: int = 1,
+        nnodes: int = 1,
+        local_mode: bool = True,
+        use_gpu: bool = True,
+        deepspeed_config=None,
+    ):
+        """
+        This class is used to run deepspeed training workloads with spark clusters. The user has the option to
+        specify the number of gpus per node and the number of nodes (the same as if running from terminal),
+        as well as specify a deepspeed configuration file.
+
+        Parameters
+        ----------
+        num_gpus: int
+            The number of GPUs to use per node (analagous to num_gpus in deepspeed command).
+
+        nnodes: int
+            The number of nodes that should be used for the run.
+
+        local_mode: bool
+            Whether or not to run the training in a distributed fashion or just locally.
+
+        use_gpu: bool
+            Boolean flag to determine whether to utilize gpus.
+
+        deepspeed_config: Union[Dict[str,Any], str] or None:
+            The configuration file to be used for launching the deepspeed application.
+            If it is a dictionary mapping parameters to values, then we will create the file.
+            If None, deepspeed will fall back to default parameters.
+        """
+        num_processes = num_gpus * nnodes
+        DEEPSPEED_SSL_CONF = "deepspeed.spark.distributor.ignoreSsl"
+        self.deepspeed_config = deepspeed_config
+        super().__init__(num_processes, local_mode, use_gpu, _ssl_conf=DEEPSPEED_SSL_CONF)
+        self.cleanup_deepspeed_conf = False
+
+    @staticmethod
+    def _get_deepspeed_config_path(deepspeed_config):
+        if isinstance(deepspeed_config, dict):
+            with tempfile.NamedTemporaryFile(mode="w+", delete=False, suffix=".json") as file:
+                json.dump(deepspeed_config, file)
+                return file.name
+        deepspeed_config_path = deepspeed_config
+        # Empty value means the deepspeed will fall back to default settings.
+        if deepspeed_config == None:
+            return ""
+        return deepspeed_config_path
+
+    @staticmethod
+    def _create_torchrun_command(
+        input_params: Dict[str, Any], train_path: str, *args: Any
+    ) -> List[str]:
+        local_mode = input_params["local_mode"]
+        num_processes = input_params["num_processes"]
+        deepspeed_config = input_params["deepspeed_config"]
+        deepspeed_config_path = DeepspeedTorchDistributor._get_deepspeed_config_path(
+            deepspeed_config
+        )
+        torchrun_args, processes_per_node = TorchDistributor._get_torchrun_args(
+            local_mode, num_processes
+        )
+        args_string = list(map(str, args))
+        command_to_run = [
+            sys.executable,
+            "-m",
+            "torch.distributed.run",
+            *torchrun_args,
+            f"--nproc_per_node={processes_per_node}",
+            train_path,
+            *args_string,
+            "-deepspeed",
+            "--deepspeed_config",
+            deepspeed_config_path,
+        ]
+        return command_to_run
+
+    @staticmethod
+    def _run_training_on_pytorch_file(
+        input_params: Dict[str, Any], train_path: str, *args: Any, **kwargs: Any
+    ) -> None:
+        if kwargs:
+            raise ValueError(
+                "DeepspeedTorchDistributor with pytorch file doesn't support key-word type arguments"
+            )
+
+        log_streaming_client = input_params.get("log_streaming_client", None)
+        training_command = DeepspeedTorchDistributor._create_torchrun_command(
+            input_params, train_path, *args
+        )
+        DeepspeedTorchDistributor._execute_command(
+            training_command, log_streaming_client=log_streaming_client
+        )
+
+    def run(self, train_object: Union[Callable, str], *args: Any, **kwargs: Any) -> Optional[Any]:
+        # If the "train_object" is a string, then we assume it's a filepath. Otherwise, we assume it's a function.

Review Comment:
   Then do we need to verify the file exist?



##########
python/pyspark/ml/torch/deepspeed/deepspeed_distributor.py:
##########
@@ -0,0 +1,143 @@
+#
+# 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 sys
+import tempfile
+from typing import (
+    Union,
+    Callable,
+    List,
+    Dict,
+    Optional,
+    Any,
+    Tuple,
+)
+
+from pyspark.ml.torch.distributor import TorchDistributor
+
+
+class DeepspeedTorchDistributor(TorchDistributor):
+    def __init__(
+        self,
+        num_gpus: int = 1,
+        nnodes: int = 1,
+        local_mode: bool = True,
+        use_gpu: bool = True,
+        deepspeed_config=None,
+    ):
+        """
+        This class is used to run deepspeed training workloads with spark clusters. The user has the option to
+        specify the number of gpus per node and the number of nodes (the same as if running from terminal),
+        as well as specify a deepspeed configuration file.
+
+        Parameters
+        ----------
+        num_gpus: int
+            The number of GPUs to use per node (analagous to num_gpus in deepspeed command).
+
+        nnodes: int
+            The number of nodes that should be used for the run.
+
+        local_mode: bool
+            Whether or not to run the training in a distributed fashion or just locally.
+
+        use_gpu: bool
+            Boolean flag to determine whether to utilize gpus.
+
+        deepspeed_config: Union[Dict[str,Any], str] or None:
+            The configuration file to be used for launching the deepspeed application.
+            If it is a dictionary mapping parameters to values, then we will create the file.
+            If None, deepspeed will fall back to default parameters.
+        """
+        num_processes = num_gpus * nnodes
+        DEEPSPEED_SSL_CONF = "deepspeed.spark.distributor.ignoreSsl"

Review Comment:
   Define a const and reuse it instead of redefine this conf?



##########
python/pyspark/ml/torch/deepspeed/deepspeed_distributor.py:
##########
@@ -0,0 +1,143 @@
+#
+# 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 sys
+import tempfile
+from typing import (
+    Union,
+    Callable,
+    List,
+    Dict,
+    Optional,
+    Any,
+    Tuple,
+)
+
+from pyspark.ml.torch.distributor import TorchDistributor
+
+
+class DeepspeedTorchDistributor(TorchDistributor):
+    def __init__(
+        self,
+        num_gpus: int = 1,
+        nnodes: int = 1,
+        local_mode: bool = True,
+        use_gpu: bool = True,
+        deepspeed_config=None,
+    ):
+        """
+        This class is used to run deepspeed training workloads with spark clusters. The user has the option to
+        specify the number of gpus per node and the number of nodes (the same as if running from terminal),
+        as well as specify a deepspeed configuration file.
+
+        Parameters
+        ----------
+        num_gpus: int
+            The number of GPUs to use per node (analagous to num_gpus in deepspeed command).
+
+        nnodes: int
+            The number of nodes that should be used for the run.
+
+        local_mode: bool
+            Whether or not to run the training in a distributed fashion or just locally.
+
+        use_gpu: bool
+            Boolean flag to determine whether to utilize gpus.
+
+        deepspeed_config: Union[Dict[str,Any], str] or None:
+            The configuration file to be used for launching the deepspeed application.
+            If it is a dictionary mapping parameters to values, then we will create the file.
+            If None, deepspeed will fall back to default parameters.
+        """
+        num_processes = num_gpus * nnodes
+        DEEPSPEED_SSL_CONF = "deepspeed.spark.distributor.ignoreSsl"
+        self.deepspeed_config = deepspeed_config
+        super().__init__(num_processes, local_mode, use_gpu, _ssl_conf=DEEPSPEED_SSL_CONF)
+        self.cleanup_deepspeed_conf = False
+
+    @staticmethod
+    def _get_deepspeed_config_path(deepspeed_config):
+        if isinstance(deepspeed_config, dict):
+            with tempfile.NamedTemporaryFile(mode="w+", delete=False, suffix=".json") as file:
+                json.dump(deepspeed_config, file)
+                return file.name
+        deepspeed_config_path = deepspeed_config
+        # Empty value means the deepspeed will fall back to default settings.
+        if deepspeed_config == None:
+            return ""
+        return deepspeed_config_path
+
+    @staticmethod
+    def _create_torchrun_command(
+        input_params: Dict[str, Any], train_path: str, *args: Any
+    ) -> List[str]:
+        local_mode = input_params["local_mode"]
+        num_processes = input_params["num_processes"]
+        deepspeed_config = input_params["deepspeed_config"]
+        deepspeed_config_path = DeepspeedTorchDistributor._get_deepspeed_config_path(
+            deepspeed_config
+        )
+        torchrun_args, processes_per_node = TorchDistributor._get_torchrun_args(
+            local_mode, num_processes
+        )
+        args_string = list(map(str, args))
+        command_to_run = [
+            sys.executable,
+            "-m",
+            "torch.distributed.run",
+            *torchrun_args,
+            f"--nproc_per_node={processes_per_node}",
+            train_path,
+            *args_string,
+            "-deepspeed",
+            "--deepspeed_config",
+            deepspeed_config_path,
+        ]
+        return command_to_run
+
+    @staticmethod
+    def _run_training_on_pytorch_file(
+        input_params: Dict[str, Any], train_path: str, *args: Any, **kwargs: Any
+    ) -> None:
+        if kwargs:
+            raise ValueError(

Review Comment:
   If it does not support kwargs, why we define it?



-- 
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