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


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

Review Comment:
   Mark these as internal function: `_execute_command`?



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