Deep Learning Using Multiple GPUs

Article ID: 656
Last updated: 01 Apr, 2025

The two deep learning frameworks supported on NAS systems, TensorFlow and PyTorch, are capable of training using multiple GPUs on the same node. In TensorFlow, the MirroredStrategy function is the best option for training using multiple GPUs on a single node. In PyTorch, the DataParallel function is the best option.

Using TensorFlow MirroredStrategy 

Using the TensorFlow MirroredStrategy framework is relatively straightforward, with only slight modifications needed to existing Python code. Complete these steps to set it up.

  1. Create a MirroredStrategy instance:
    mirrored_strategy = tf.distribute.MirroredStrategy()

  2. Create, compile, and fit the model in the scope of the MirroredStrategy:
    with mirrored_strategy.scope():
        model = Model()
        model.compile(loss = …, optimizer = …, …)
        model.fit(x_train, y_train, batch_size, epochs, …)
    

    This approach allows TensorFlow to effectively use all of the GPUs attached to the node. If you want to use only a few of the GPUs in a node to train a model, then you must assign the GPUs to the MirroredStrategy, as follows:
    mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
    The model will be trained using only the assigned GPUs.

Using PyTorch DataParallel

The basic principle behind PyTorch DataParallel is to allocate the data and model to the GPUs, rather than the CPUs. Complete these steps to set it up.

  1. Create the device object:
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

  2. Move the model to the device:
    model = nn_model()
    model = nn.DataParallel(model)
    model.to(device)

  3. Assign the data to the GPUs by applying the *.cuda() function to the torch tensor. For example:
    gpu_data = torch.tensor(data).cuda()

The model can now be trained on the GPUs using existing PyTorch code.

Multiple GPU Node Training Using PyTorch Lightning

PyTorch Lightning is an API for the PyTorch training loop. PyTorch Lightning also has functionality to train deep learning models using multiple GPU nodes. Setting up this feature on NAS systems can be complex. Complete these steps to set it up.

  1. In your Python code, update the PyTorch Lightning trainer for multi-node uses.
    • For older versions of PyTorch Lightning (those in the NAS pyt1_12 and pyt1_13 conda environments) do:
      trainer = pl.Trainer(gpus=number_gpus_on_each_node, 
                                             num_nodes=number_of_nodes, 
                                             strategy="ddp",
                                             .... other_flags)

    • For newer versions of PyTorch Lightning, do:
      trainer = pl.Trainer(accelerator='gpu', 
                                             devices=number_gpus_on_each_node, 
                                             num_nodes=number_of_nodes,
                                             strategy="ddp", 
                                             .... other_flags)

  2. Now, you need to set up the cluster environment so Lightning can do the rest. To do so, you must first collect information about the environment.

    • Collect the node names by using the following bash script:
      NODES=($( cat $PBS_NODEFILE | uniq ))
      NUM_OF_NODES=${#NODES[@]}

    • Collect the following information: the port on the master node that will be used for communication (MASTER_PORT - this can be any open unused port); the total number of GPUs over all the nodes (WORLD_SIZE); and the rank of the current node (NODE_RANK). You also need to obtain the IP address of the master node (MASTER_ADDR); to do this, ping the master node:
      ping ${NODES[0]} -c 2 > master_ip.txt

      The resulting text file will contain the IP address and other information:

      PING r101i0n6.p4.nas.nasa.gov (10.150.39.109) 56(84) bytes of data.
      64 bytes from r101i0n6.p4.nas.nasa.gov (10.150.39.109): icmp_seq=1 ttl=64 time=0.017 ms
      64 bytes from r101i0n6.p4.nas.nasa.gov (10.150.39.109): icmp_seq=2 ttl=64 time=0.031 ms
      
      --- r101i0n6.p4.nas.nasa.gov ping statistics ---
      2 packets transmitted, 2 received, 0% packet loss, time 1053ms
      rtt min/avg/max/mdev = 0.017/0.024/0.031/0.007 ms

      This information must be parsed to collect the IP address, 10.150.39.107. You can use Python to do the parsing. For example:

      #This code parses ping output text to get host address
      #
      with open('master_ip.txt', 'r') as f:
          ip = f.readlines()
      
      with open('ip.txt', 'w') as f:
          f.write(ip[0].split('(')[1].split(')')[0])

      The resulting file contains the IP address, which you can then assign to the MASTER_ADDR environment variable in the next step.

  3. Assign the environment variables in your PBS script, using the information you gathered in step 2:
    export MASTER_PORT=12018
    export MASTER_ADDR=`cat ip.txt`
    export WORLD_SIZE=$TOTAL_NUM_GPS 
    

    where TOTAL_NUM_GPS = the total number of GPUs across all nodes.
     

    Note: For GH200 nodes, change the line export MASTER_ADDR=`cat ip.txt` to export MASTER_ADDR=$(eval hostname)

  4. Pass the cluster information to each node and run your Python code on each node. One way to do this is to run a for loop in you PBS script:
    #the rank of the node
    C=1
    
    # for each node that's not the current node
    for node in ${NODES[@]}
    do
      if [[ $node != $(eval hostname) ]]  
      then
        # ssh into each node and run the .sh script with node info
        ssh $node "$BASE/./setup_workers.sh $MASTER_PORT $MASTER_ADDR $WORLD_SIZE $C" &
        C=$(($C+1))
        sleep 2
      fi
    done

    where setup_workers.sh is the shell script that will prepare the other nodes and run your Python code.

    Note: For GH200 nodes, change the line if [[ $node != $(eval hostname) ]] to if [[ $node != $(eval hostname --long) ]]

  5. In the shell script, do the following:

    • Change directory to the code location:
      cd /path_to_code_location

    • Load the data science conda environments. This example uses the pyt2_0 conda environment:
      #load module command
             source /usr/local/lib/global.profile
      
      #load module and activate conda environment
      module purge 
      module use -a /swbuild/analytix/tools/modulefiles
      module load miniconda3/v4
      source activate pyt2_0
      

    • Set up the cluster environment:
      export MASTER_PORT=$1
      export MASTER_ADDR=$2
      export WORLD_SIZE=$3
      
      #setup gpu
      export CUDA_VISIBLE_DEVICES=0,1,2,3
      #for GH200 setting CUDA_VISIBLE_DEVICES in not necessary when using PyTorch Lightning
      
        
      # set NCCL to use ip-over-infiniband rather than default RoCE, 
      #since our infiniband does not have RoCE
      export NCCL_IB_DISABLE=1
      

    • Run the Python code:
      NODE_RANK=$4 python your_python_code.py

  6. Back in your PBS script, you need to run the same commands (except for the MASTER_PORT, MASTER_ADDR, and WORLD_SIZE environment variable you've already created):

    #setup GPUs
    export CUDA_VISIBLE_DEVICES=0,1,2,3
    
    # set NCCL to use ip-over-infiniband rather than default RoCE, 
    #since our infiniband does not have RoCE
    export NCCL_IB_DISABLE=1
    
    module purge
    module use -a /swbuild/analytix/tools/modulefiles
    module load miniconda3/v4
    source activate pyt2_0
    
    NODE_RANK=0 python your_python_code.py

Related Resources

Contact Us

General User Assistance

Security

  • Report security issues 24x7x365
  • Toll-free: 1-877-NASA-SEC (1-877-627-2732)
  • E-mail: soc@nasa.gov

User Documentation

High-End Computing Capability (HECC) Portfolio Office

NASA High-End Computing Program

Tell Us About It

Our goal is furnish all the information you need to efficiently and effectively use the HECC resources needed for your NASA computational projects.

We welcome your input on features and topics that you would like to see included on this website.

Please send us email with your wish list and other feedback.