You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by GitBox <gi...@apache.org> on 2022/12/29 18:32:14 UTC

[GitHub] [spark] rithwik-db commented on a diff in pull request #39188: [WIP][SPARK-41591][PYTHON][ML] Training PyTorch Files on Single Node Multi GPU

rithwik-db commented on code in PR #39188:
URL: https://github.com/apache/spark/pull/39188#discussion_r1059097298


##########
python/pyspark/ml/torch/distributor.py:
##########
@@ -0,0 +1,491 @@
+#
+# 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 collections
+import ctypes
+import math
+import os
+import random
+import re
+import signal
+import sys
+import subprocess
+import time
+from typing import Union, Callable, Optional, Any
+import warnings
+
+from pyspark.sql import SparkSession
+from pyspark.context import SparkContext
+
+
+# Moved the util functions to this file for now
+# TODO(SPARK-41589): will move the functions and tests to an external file
+#       once we are in agreement about which functions should be in utils.py
+def get_conf_boolean(sc: SparkContext, key: str, default_value: str) -> bool:
+    """Get the conf "key" from the given spark context,
+    or return the default value if the conf is not set.
+    This expects the conf value to be a boolean or string;
+    if the value is a string, this checks for all capitalization
+    patterns of "true" and "false" to match Scala.
+
+    Parameters
+    ----------
+    sc : SparkContext
+        The SparkContext for the distributor.
+    key : str
+        string for conf name
+    default_value : str
+        default value for the conf value for the given key
+
+    Returns
+    -------
+    bool
+        Returns the boolean value that corresponds to the conf
+
+    Raises
+    ------
+    Exception
+        Thrown when the conf value is not a boolean
+    """
+    val = sc.getConf().get(key, default_value)
+    lowercase_val = val.lower()
+    if lowercase_val == "true":
+        return True
+    if lowercase_val == "false":
+        return False
+    raise Exception(
+        "get_conf_boolean expected a boolean conf "
+        "value but found value of type {} "
+        "with value: {}".format(type(val), val)
+    )
+
+
+def get_gpus_owned(addresses: list[str]) -> list[str]:
+    """
+    Gets the number of GPUs that Spark scheduled to the calling task.
+    Returns:
+        The number of GPUs that Spark scheduled to the calling task.
+    """
+    CUDA_VISIBLE_DEVICES = "CUDA_VISIBLE_DEVICES"
+    pattern = re.compile("^[1-9][0-9]*|0$")
+    if any(not pattern.match(address) for address in addresses):
+        raise ValueError(
+            f"Found GPU addresses {addresses} which "
+            "are not all in the correct format "
+            "for CUDA_VISIBLE_DEVICES, which requires "
+            "integers with no zero padding."
+        )
+    if CUDA_VISIBLE_DEVICES in os.environ:
+        gpu_indices = list(map(int, addresses))
+        gpu_list = os.environ[CUDA_VISIBLE_DEVICES].split(",")
+        gpu_owned = [gpu_list[i] for i in gpu_indices]
+        return gpu_owned
+    return addresses
+
+
+def create_torchrun_command(input_params: dict[str, Any], train_path: str, *args: Any) -> list[str]:
+    """Returns the expected torchrun command based on the input.
+
+    Parameters
+    ----------
+    input_params : dict[str, Any]
+        The dictionary of the input parameters of the distributor. The most relevant params
+        are local_mode and num_processes.
+    train_path : str
+        The path to the (potentially autogenerated) train.py file
+    args: *args
+        The input arguments to the train.py file.
+
+    Returns
+    -------
+    str
+        The output torchrun command
+    """
+    local_mode = input_params["local_mode"]
+    num_processes = input_params["num_processes"]
+
+    if local_mode:
+        standalone = ["--standalone", "--nnodes=1"]
+        processes_per_node = num_processes
+    else:
+        master_addr, master_port = os.environ["MASTER_ADDR"], os.environ["MASTER_PORT"]
+        node_rank = os.environ["RANK"]
+        standalone = [
+            f"--nnodes={num_processes}",
+            f"--node_rank={node_rank}",
+            f"--rdzv_endpoint={master_addr}:{master_port}",
+            "--rdzv_id=0",
+        ]  # TODO: setup random ID that is gleaned from env variables
+        processes_per_node = 1
+
+    args_string = list(map(str, args))  # converting all args to strings
+
+    return (
+        ["torchrun"]
+        + standalone
+        + [f"--nproc_per_node={processes_per_node}"]
+        + [train_path, *args_string]
+    )
+
+
+def execute_command(cmd: list[str], _prctl: bool = True, redirect_to_stdout: bool = True) -> None:
+    """Runs a command in a new process, redirects stdout/stderr to stdout, and handles termination
+    of the command process.
+
+    Parameters
+    ----------
+    cmd : list[str]
+        The users's input command split by the space characeter
+    _prctl : bool, optional
+        (test only) Use prctl to signal the command process upon parent death, by default True
+    redirect_to_stdout : bool, optional
+        whether to redirect all stdout/stderr logs to current stdout, by default True
+    TODO(SPARK-41593): Will update with additional parameters for logging to driver
+
+    Raises
+    ------
+    RuntimeError
+        If the child executed command fails
+    """
+    _TAIL_LINES_TO_KEEP = 100
+
+    def sigterm_on_parent_death() -> None:
+        """
+        Uses prctl to automatically send SIGTERM to the command process when its parent is dead.
+        This handles the case when the parent is a PySpark worker process.
+        If a user cancels the PySpark job, the worker process gets killed, regardless of
+        PySpark daemon and worker reuse settings.
+        NOTE: This doesn't work on windows or POSIX.
+        Future reference:
+        - MacOS/POSIX: https://stackoverflow.com/a/2035683
+        - Windows: https://stackoverflow.com/a/23587108
+        """
+        if _prctl:
+            try:
+                libc = ctypes.CDLL("libc.so.6")
+                # Set the parent process death signal of the command process to SIGTERM.
+                libc.prctl(1, signal.SIGTERM)
+            except OSError:
+                pass
+
+    task = subprocess.Popen(
+        cmd,
+        stdout=subprocess.PIPE,
+        stderr=subprocess.STDOUT,
+        stdin=subprocess.PIPE,
+        env=os.environ,  # preserve the environ to support nested MPI jobs
+        preexec_fn=sigterm_on_parent_death,
+    )
+    task.stdin.close()  # type: ignore
+    tail: collections.deque = collections.deque(maxlen=_TAIL_LINES_TO_KEEP)
+    try:
+        for line in task.stdout:  # type: ignore
+            decoded = line.decode()
+            tail.append(decoded)
+            if redirect_to_stdout:
+                sys.stdout.write(decoded)
+        task.wait()
+    finally:
+        if task.poll() is None:
+            try:
+                task.terminate()  # SIGTERM
+                time.sleep(0.5)
+                if task.poll() is None:
+                    task.kill()  # SIGKILL
+            except OSError:
+                pass
+    if task.returncode != os.EX_OK:
+        if len(tail) == _TAIL_LINES_TO_KEEP:
+            last_n_msg = f"last {_TAIL_LINES_TO_KEEP} lines of the task output are"
+        else:
+            last_n_msg = "task output is"
+        task_output = "".join(tail)
+        raise RuntimeError(
+            f"Command {cmd} failed with return code {task.returncode}."
+            f"The {last_n_msg} included below: {task_output}"
+        )
+
+
+class Distributor:
+    def __init__(
+        self,
+        num_processes: int = 1,
+        local_mode: bool = True,

Review Comment:
   @lu-wang-dl is this okay with you?



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