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


##########
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,
+        use_gpu: bool = True,
+        spark: Optional[SparkSession] = None,
+    ):
+        self.num_processes = num_processes
+        self.local_mode = local_mode
+        self.use_gpu = use_gpu
+        if spark:
+            self.spark = spark
+        else:
+            self.spark = SparkSession.builder.getOrCreate()
+        self.sc = self.spark.sparkContext
+        self.num_tasks = self._get_num_tasks()
+        self.ssl_conf = None
+
+    def _get_num_tasks(self) -> int:
+        """
+        Returns the number of Spark tasks to use for distributed training
+
+        Returns
+        -------
+            The number of Spark tasks to use for distributed training
+        """
+        if self.use_gpu:
+            key = "spark.task.resource.gpu.amount"
+            if self.sc.getConf().contains(key):
+                if gpu_amount_raw := self.sc.getConf().get(key):  # mypy 
error??
+                    task_gpu_amount = int(gpu_amount_raw)
+            else:
+                task_gpu_amount = 1  # for single node clusters
+            if task_gpu_amount < 1:
+                raise ValueError(
+                    f"The Spark conf `{key}` has a value "
+                    f"of {task_gpu_amount} but it "
+                    "should not have a value less than 1."
+                )
+            return math.ceil(self.num_processes / task_gpu_amount)
+        return self.num_processes
+
+    def _validate_input_params(self) -> None:
+        if self.num_processes <= 0:
+            raise ValueError("num_proccesses has to be a positive integer")
+
+    def _check_encryption(self) -> None:
+        """Checks to see if the user requires encrpytion of data.
+        If required, throw an exception since we don't support that.
+
+        Raises
+        ------
+        NotImplementedError
+            Thrown when the user doesn't use PyTorchDistributor
+        Exception
+            Thrown when the user requires ssl encryption
+        """
+        if not "ssl_conf":
+            raise Exception(
+                "Distributor doesn't have this functionality. Use 
PyTorchDistributor instead."
+            )
+        is_ssl_enabled = get_conf_boolean(self.sc, "spark.ssl.enabled", 
"false")
+        ignore_ssl = get_conf_boolean(self.sc, self.ssl_conf, "false")  # 
type: ignore
+        if is_ssl_enabled:
+            name = self.__class__.__name__
+            if ignore_ssl:
+                warnings.warn(
+                    f"""
+                    This cluster has TLS encryption enabled;
+                    however, {name} does not
+                    support data encryption in transit.
+                    The Spark configuration
+                    '{self.ssl_conf}' has been set to
+                    'true' to override this
+                    configuration and use {name} anyway. Please
+                    note this will cause model
+                    parameters and possibly training data to
+                    be sent between nodes unencrypted.
+                    """,
+                    RuntimeWarning,
+                )
+                return
+            raise Exception(
+                f"""
+                This cluster has TLS encryption enabled;
+                however, {name} does not support
+                data encryption in transit. To override
+                this configuration and use {name}
+                anyway, you may set '{self.ssl_conf}'
+                to 'true' in the Spark configuration. Please note this
+                will cause model parameters and possibly training
+                data to be sent between nodes unencrypted.
+                """
+            )
+
+
+class PyTorchDistributor(Distributor):
+    """
+    A class to support distributed training on PyTorch and PyTorch Lightning 
using PySpark.
+
+    .. versionadded:: 3.4.0
+
+    Examples
+    --------
+
+    Run PyTorch Training locally on GPU (using a PyTorch native function)
+
+    >>> def train(learning_rate):
+    >>>     import torch.distributed
+    >>>     torch.distributed.init_process_group(backend="nccl")
+    >>>     ...
+    >>>     torch.destroy_process_group()
+    >>> distributor = Distributor(framework="pytorch",
+                                  num_processes=2,
+                                  local_mode=True,
+                                  use_gpu=True)
+    >>> distributor.run(train, 1e-3)
+
+    Run PyTorch Training on GPU (using a file with PyTorch code)
+
+    >>> distributor = Distributor(framework="pytorch",
+                                  num_processes=2,
+                                  local_mode=False,
+                                  use_gpu=True)
+    >>> distributor.run(/path/to/train.py, *args)
+
+    Run PyTorch Lightning Training
+    >>> def train():
+    >>>     from pytorch_lightning import Trainer
+    >>>     ...
+    >>>     trainer = Trainer(accelerator="gpu", devices=8, num_nodes=4, 
strategy="ddp")
+    >>>     trainer.fit()
+    >>>     ...
+    >>>     return trainer
+    >>> distributor = Distributor(framework="pytorch-lightning",
+                                  num_processes=2,
+                                  local_mode=True,
+                                  use_gpu=True)
+    >>> trainer = distributor.run(train)
+    """
+
+    available_frameworks = ["pytorch", "pytorch-lightning"]
+    PICKLED_FUNC_FILE = "func.pickle"
+    TRAIN_FILE = "train.py"
+
+    def __init__(
+        self,
+        framework: str,
+        num_processes: int = 1,
+        local_mode: bool = True,
+        use_gpu: bool = True,
+        spark: Optional[SparkSession] = None,
+    ):
+        """Initializes the distributor.
+
+        Parameters
+        ----------
+        framework : str
+            A string indicating whether or not we are using PyTorch or PyTorch
+            Lightning. This could either be the string “pytorch” or 
”pytorch-lightning”.
+        num_processes : int, optional
+            An integer that determines how many different concurrent
+            tasks are allowed. We expect spark.task.gpus = 1 for GPU-enabled 
training. Default
+            should be 1; we don't want to invoke multiple cores/gpus without 
explicit mention.
+        local_mode : bool, optional
+            A boolean that determines whether we are using the driver
+            node for training. Default should be false; we don't want to 
invoke executors without
+            explicit mention.
+        use_gpu : bool, optional
+            A boolean that indicates whether or not we are doing training
+            on the GPU. Note that there are differences in how GPU-enabled 
code looks like and
+            how CPU-specific code looks like.
+        spark : Optional[SparkSession], optional
+            An optional parameter that allows users to pass in a custom 
SparkSession argument
+            with a custom conf, by default None
+
+        Raises
+        ------
+        ValueError
+            If any of the parameters are incorrect.
+        """
+        super().__init__(num_processes, local_mode, use_gpu, spark)
+        self.framework = framework
+        self.ssl_conf = "pytorch.spark.distributor.ignoreSsl"  # type: ignore
+        self._validate_input_params()
+
+    def _validate_input_params(self) -> None:
+        """Validates input params
+
+        Raises
+        ------
+        ValueError
+            Thrown when user fails to provide correct input params
+        """
+        super()._validate_input_params()
+        if self.framework not in self.available_frameworks:
+            raise ValueError(
+                f"{self.framework} is not a valid framework."
+                f"Available frameworks: {self.available_frameworks}"
+            )
+
+    def _run_local_training(
+        self,
+        framework_wrapper_fn: Optional[Callable],
+        train_fn: Union[Callable, str],
+        *args: Any,
+    ) -> Optional[Any]:
+        CUDA_VISIBLE_DEVICES = "CUDA_VISIBLE_DEVICES"
+        old_cuda_visible_devices = os.environ.get(CUDA_VISIBLE_DEVICES, "")
+        cuda_state_was_set = CUDA_VISIBLE_DEVICES in os.environ
+        if not framework_wrapper_fn:
+            raise RuntimeError("Unknown combination of parameters")
+        try:
+            if self.use_gpu:
+                if "gpu" not in self.sc.resources:
+                    raise ValueError('"gpu" was not found in the context 
resources.')

Review Comment:
   But we would need to inform the user that setting `use_gpu=True` lead to 
that issue. Alternatively, we could tell the user that gpu was not found so we 
will switch to cpu through logging,



##########
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,
+        use_gpu: bool = True,
+        spark: Optional[SparkSession] = None,
+    ):
+        self.num_processes = num_processes
+        self.local_mode = local_mode
+        self.use_gpu = use_gpu
+        if spark:
+            self.spark = spark
+        else:
+            self.spark = SparkSession.builder.getOrCreate()
+        self.sc = self.spark.sparkContext
+        self.num_tasks = self._get_num_tasks()
+        self.ssl_conf = None
+
+    def _get_num_tasks(self) -> int:
+        """
+        Returns the number of Spark tasks to use for distributed training
+
+        Returns
+        -------
+            The number of Spark tasks to use for distributed training
+        """
+        if self.use_gpu:
+            key = "spark.task.resource.gpu.amount"
+            if self.sc.getConf().contains(key):
+                if gpu_amount_raw := self.sc.getConf().get(key):  # mypy 
error??
+                    task_gpu_amount = int(gpu_amount_raw)
+            else:
+                task_gpu_amount = 1  # for single node clusters
+            if task_gpu_amount < 1:
+                raise ValueError(
+                    f"The Spark conf `{key}` has a value "
+                    f"of {task_gpu_amount} but it "
+                    "should not have a value less than 1."
+                )
+            return math.ceil(self.num_processes / task_gpu_amount)
+        return self.num_processes
+
+    def _validate_input_params(self) -> None:
+        if self.num_processes <= 0:
+            raise ValueError("num_proccesses has to be a positive integer")
+
+    def _check_encryption(self) -> None:
+        """Checks to see if the user requires encrpytion of data.
+        If required, throw an exception since we don't support that.
+
+        Raises
+        ------
+        NotImplementedError
+            Thrown when the user doesn't use PyTorchDistributor
+        Exception
+            Thrown when the user requires ssl encryption
+        """
+        if not "ssl_conf":
+            raise Exception(
+                "Distributor doesn't have this functionality. Use 
PyTorchDistributor instead."
+            )
+        is_ssl_enabled = get_conf_boolean(self.sc, "spark.ssl.enabled", 
"false")
+        ignore_ssl = get_conf_boolean(self.sc, self.ssl_conf, "false")  # 
type: ignore
+        if is_ssl_enabled:
+            name = self.__class__.__name__
+            if ignore_ssl:
+                warnings.warn(
+                    f"""
+                    This cluster has TLS encryption enabled;
+                    however, {name} does not
+                    support data encryption in transit.
+                    The Spark configuration
+                    '{self.ssl_conf}' has been set to
+                    'true' to override this
+                    configuration and use {name} anyway. Please
+                    note this will cause model
+                    parameters and possibly training data to
+                    be sent between nodes unencrypted.
+                    """,
+                    RuntimeWarning,
+                )
+                return
+            raise Exception(
+                f"""
+                This cluster has TLS encryption enabled;
+                however, {name} does not support
+                data encryption in transit. To override
+                this configuration and use {name}
+                anyway, you may set '{self.ssl_conf}'
+                to 'true' in the Spark configuration. Please note this
+                will cause model parameters and possibly training
+                data to be sent between nodes unencrypted.
+                """
+            )
+
+
+class PyTorchDistributor(Distributor):
+    """
+    A class to support distributed training on PyTorch and PyTorch Lightning 
using PySpark.
+
+    .. versionadded:: 3.4.0
+
+    Examples
+    --------
+
+    Run PyTorch Training locally on GPU (using a PyTorch native function)
+
+    >>> def train(learning_rate):
+    >>>     import torch.distributed
+    >>>     torch.distributed.init_process_group(backend="nccl")
+    >>>     ...
+    >>>     torch.destroy_process_group()
+    >>> distributor = Distributor(framework="pytorch",
+                                  num_processes=2,
+                                  local_mode=True,
+                                  use_gpu=True)
+    >>> distributor.run(train, 1e-3)
+
+    Run PyTorch Training on GPU (using a file with PyTorch code)
+
+    >>> distributor = Distributor(framework="pytorch",
+                                  num_processes=2,
+                                  local_mode=False,
+                                  use_gpu=True)
+    >>> distributor.run(/path/to/train.py, *args)
+
+    Run PyTorch Lightning Training
+    >>> def train():
+    >>>     from pytorch_lightning import Trainer
+    >>>     ...
+    >>>     trainer = Trainer(accelerator="gpu", devices=8, num_nodes=4, 
strategy="ddp")
+    >>>     trainer.fit()
+    >>>     ...
+    >>>     return trainer
+    >>> distributor = Distributor(framework="pytorch-lightning",
+                                  num_processes=2,
+                                  local_mode=True,
+                                  use_gpu=True)
+    >>> trainer = distributor.run(train)
+    """
+
+    available_frameworks = ["pytorch", "pytorch-lightning"]
+    PICKLED_FUNC_FILE = "func.pickle"
+    TRAIN_FILE = "train.py"
+
+    def __init__(
+        self,
+        framework: str,
+        num_processes: int = 1,
+        local_mode: bool = True,
+        use_gpu: bool = True,
+        spark: Optional[SparkSession] = None,
+    ):
+        """Initializes the distributor.
+
+        Parameters
+        ----------
+        framework : str
+            A string indicating whether or not we are using PyTorch or PyTorch
+            Lightning. This could either be the string “pytorch” or 
”pytorch-lightning”.
+        num_processes : int, optional
+            An integer that determines how many different concurrent
+            tasks are allowed. We expect spark.task.gpus = 1 for GPU-enabled 
training. Default
+            should be 1; we don't want to invoke multiple cores/gpus without 
explicit mention.
+        local_mode : bool, optional
+            A boolean that determines whether we are using the driver
+            node for training. Default should be false; we don't want to 
invoke executors without
+            explicit mention.
+        use_gpu : bool, optional
+            A boolean that indicates whether or not we are doing training
+            on the GPU. Note that there are differences in how GPU-enabled 
code looks like and
+            how CPU-specific code looks like.
+        spark : Optional[SparkSession], optional
+            An optional parameter that allows users to pass in a custom 
SparkSession argument
+            with a custom conf, by default None
+
+        Raises
+        ------
+        ValueError
+            If any of the parameters are incorrect.
+        """
+        super().__init__(num_processes, local_mode, use_gpu, spark)
+        self.framework = framework
+        self.ssl_conf = "pytorch.spark.distributor.ignoreSsl"  # type: ignore
+        self._validate_input_params()
+
+    def _validate_input_params(self) -> None:
+        """Validates input params
+
+        Raises
+        ------
+        ValueError
+            Thrown when user fails to provide correct input params
+        """
+        super()._validate_input_params()
+        if self.framework not in self.available_frameworks:
+            raise ValueError(
+                f"{self.framework} is not a valid framework."
+                f"Available frameworks: {self.available_frameworks}"
+            )
+
+    def _run_local_training(
+        self,
+        framework_wrapper_fn: Optional[Callable],
+        train_fn: Union[Callable, str],
+        *args: Any,
+    ) -> Optional[Any]:
+        CUDA_VISIBLE_DEVICES = "CUDA_VISIBLE_DEVICES"
+        old_cuda_visible_devices = os.environ.get(CUDA_VISIBLE_DEVICES, "")
+        cuda_state_was_set = CUDA_VISIBLE_DEVICES in os.environ
+        if not framework_wrapper_fn:
+            raise RuntimeError("Unknown combination of parameters")
+        try:
+            if self.use_gpu:
+                if "gpu" not in self.sc.resources:
+                    raise ValueError('"gpu" was not found in the context 
resources.')

Review Comment:
   But we would need to inform the user that setting `use_gpu=True` lead to 
that issue. Alternatively, we could tell the user that gpu was not found so we 
will switch to cpu through logging.



-- 
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-unsubscr...@spark.apache.org

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


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

Reply via email to