Help Center/ ModelArts/ ModelArts User Guide (Lite Server)/ Using Lite Server Resources/ PyTorch GPU Training and Inference Guide for GPT-2
Updated on 2024-11-19 GMT+08:00

PyTorch GPU Training and Inference Guide for GPT-2

Scenario

This section describes how to use the DeepSpeed framework to train GPT-2 in a GP Ant8 BMS (single-node single-card and single-node multi-card). After the training, the automatically generated content and interactive dialog box mode are provided.

Background

  • Megatron-DeepSpeed

    Deepspeed is a PyTorch-based deep learning model training framework. It combines Megatron-LM and DeepSpeed to train on systems with distributed computing, and takes full advantage of the parallel processing capabilities of multiple GPUs and deep learning accelerators. Large-scale language models can be efficiently trained.

    Megatron-LM is a model for large-scale language modeling. Based on the Generative Pre-trained Transformer (GPT) architecture, it is a neural network model based on the self-attention mechanism and is widely used in natural language processing tasks, such as text generation, machine translation, and dialog systems.

    DeepSpeed is an open-source library for accelerating deep learning training. It is optimized for large-scale model and distributed training, which can significantly improve the training speed and efficiency. DeepSpeed provides various technologies and optimization policies, including distributed gradient descent, model parallelization, gradient accumulation, and dynamic precision scaling. It also supports optimizing the memory usage and compute resource allocation of foundation models.

  • GPT2

    GPT2 is a new pre-trained model released by OpenAI based on the GPT model in 2018. It is a large language model based on Transformer. It is trained on a large number of datasets and directly runs a pre-trained GPT-2 model. Given a preset start word or sentence, it can randomly generate subsequent text.

Preparing the Environment

Purchase a GPU-powered BMS on ModelArts and select a general-purpose image for AIGC to train a GPT2 model. The following images and specifications are used as example:

  • Image: Ubuntu 20.04 x86 64bit SDI3 for Ant8 BareMetal with RoCE and NVIDIA-525 CUDA-12.0
  • BMS specifications: GP Ant8, including eight GPU cards and eight RoCE NICs

To purchase an Ant8 BMS, submit a service ticket on the Huawei Cloud official website.

Step 1 Installing a Model

  1. Install the Megatron-DeepSpeed framework.

    1. Log in to the GPU BMS using SSH as user root.
    2. Pull the PyTorch image. You can download a common image source.
      docker pull nvcr.io/nvidia/pytorch:21.10-py3
    3. Start the container.
      docker run -d -t --network=host --gpus all --privileged --ipc=host --ulimit memlock=-1 --ulimit stack=67108864 --name megatron-deepspeed -v /etc/localtime:/etc/localtime -v /root/.ssh:/root/.ssh nvcr.io/nvidia/pytorch:21.10-py3
    4. Access the container terminal.
      docker exec -it megatron-deepspeed bash
    5. Download the Megatron-DeepSpeed framework.
      git clone https://github.com/bigscience-workshop/Megatron-DeepSpeed

      If the git clone fails to be executed, download the model to the local host, copy it to the server, and run the docker cp command to copy it to the container.

    6. Install the Megatron-DeepSpeed framework.
      cd Megatron-DeepSpeed
      pip install -r requirements.txt -i http://mirrors.myhuaweicloud.com/pypi/web/simple --trusted-host mirrors.myhuaweicloud.com
      pip install mpi4py -i http://mirrors.myhuaweicloud.com/pypi/web/simple --trusted-host mirrors.myhuaweicloud.com
    7. Modify the test code and comment out the line where the assertion is located.
      vim /workspace/Megatron-DeepSpeed/megatron/model/fused_softmax.py +191

      Add # before assert mask is None, "Mask is silently ignored due to the use of a custom kernel".

      # assert mask is None, "Mask is silently ignored due to the use of a custom kernel"

  2. Download and preprocess the dataset.

    The OSCAR dataset in JSON format with 1 GB 79K-record is used.

    1. Download the dataset.
      wget https://huggingface.co/bigscience/misc-test-data/resolve/main/stas/oscar-1GB.jsonl.xz 
      wget https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-vocab.json
      wget https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-merges.txt
    2. Decompress the dataset.
      xz -d oscar-1GB.jsonl.xz
    3. Preprocess data.
      python3 tools/preprocess_data.py \
          --input oscar-1GB.jsonl \
          --output-prefix meg-gpt2 \
          --vocab gpt2-vocab.json \
          --dataset-impl mmap \
          --tokenizer-type GPT2BPETokenizer \
          --merge-file gpt2-merges.txt \
          --append-eod \
          --workers 8
      If the error message "np.float" is displayed, change it to "float" as prompted.
      Figure 1 Data preprocessing error
    4. Complete the preprocessing.
      Figure 2 Data preprocessed
    5. Create the data directory and move the processed data.
      mkdir data 
      mv meg-gpt2* ./data 
      mv gpt2* ./data

Step 2 Single-Node Single-Card Training

This section describes how to use a GP Ant8 BMS to train the GPT-2 MEDIUM model on a single node.

  1. Create the pre-training script file.

    1. Create the script.
      vim pretrain_gpt2.sh
    2. Add the following information to the script:
      #! /bin/bash
      
      # Runs the "345M" parameter model
      
      GPUS_PER_NODE=1
      # Change for multinode config
      MASTER_ADDR=localhost
      MASTER_PORT=6000
      NNODES=1
      NODE_RANK=0
      WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES))
      
      DATA_PATH=data/meg-gpt2_text_document
      CHECKPOINT_PATH=checkpoints/gpt2
      
      DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT"
      
      python -m torch.distributed.launch $DISTRIBUTED_ARGS \
             pretrain_gpt.py \
             --tensor-model-parallel-size 1 \
             --pipeline-model-parallel-size 1 \
             --num-layers 24 \
             --hidden-size 1024 \
             --num-attention-heads 16 \
             --micro-batch-size 4 \
             --global-batch-size 8 \
             --seq-length 1024 \
             --max-position-embeddings 1024 \
             --train-iters 5000 \
             --lr-decay-iters 320000 \
             --save $CHECKPOINT_PATH \
             --load $CHECKPOINT_PATH \
             --data-path $DATA_PATH \
             --vocab-file data/gpt2-vocab.json \
             --merge-file data/gpt2-merges.txt \
             --data-impl mmap \
             --split 949,50,1 \
             --distributed-backend nccl \
             --lr 0.00015 \
             --lr-decay-style cosine \
             --min-lr 1.0e-5 \
             --weight-decay 1e-2 \
             --clip-grad 1.0 \
             --lr-warmup-fraction .01 \
             --checkpoint-activations \
             --log-interval 10 \
             --save-interval 500 \
             --eval-interval 100 \
             --eval-iters 10 \
             --fp16

  2. Start training.

    Configure the parameters in the pre-training script for the single-node single-card training.

    GPUS_PER_NODE=1
    NNODES=1
    NODE_RANK=0
    1. Start the pre-training.
      nohup sh ./pretrain_gpt2.sh &
      Figure 3 Starting pre-training
    2. View training logs and monitor programs in real time.
      tail -f nohup.out

      If the following information is displayed, the model is trained.

      Figure 4 Model training completed

      Observe GPU usage during training.

      Figure 5 GPU usage

  3. View the checkpoint of the generated model.

    The checkpoint of the model used in this case is saved in /workspace/Megatron-DeepSpeed/checkpoints/gpt2.

    ll ./checkpoints/gpt2
    Figure 6 Model checkpoint

Step 3 Single-Node Multi-Card Training

Compared with single-node single-card training, single-node multi-card training only needs to set multi-card parameters in the pre-training script. Other steps are the same as those of single-node single-card training.

  1. Currently, eight GPUs are selected for BMS. Adjust the parameters.

    GPUS_PER_NODE=8

  2. Configure the global batch size, micro batch size, and data_parallel_size parameters. The value of global_batch_size can be exactly divided by the value of micro_batch_size * data_parallel_size.

    Configure the parameters.

    global_batch_size = 64 
    micro_batch_size = 4 
    data_parallel_size = 8

  3. The content of the pre-training script is as follows:

    #! /bin/bash
    
    # Runs the "345M" parameter model
    
    GPUS_PER_NODE=8
    # Change for multinode config
    MASTER_ADDR=localhost
    MASTER_PORT=6000
    NNODES=1
    NODE_RANK=0
    WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES))
    
    DATA_PATH=data/meg-gpt2_text_document
    CHECKPOINT_PATH=checkpoints/gpt2
    
    DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT"
    
    python -m torch.distributed.launch $DISTRIBUTED_ARGS \
           pretrain_gpt.py \
           --tensor-model-parallel-size 1 \
           --pipeline-model-parallel-size 1 \
           --num-layers 24 \
           --hidden-size 1024 \
           --num-attention-heads 16 \
           --micro-batch-size 4 \
           --global-batch-size 64 \
           --seq-length 1024 \
           --max-position-embeddings 1024 \
           --train-iters 5000 \
           --lr-decay-iters 320000 \
           --save $CHECKPOINT_PATH \
           --load $CHECKPOINT_PATH \
           --data-path $DATA_PATH \
           --vocab-file data/gpt2-vocab.json \
           --merge-file data/gpt2-merges.txt \
           --data-impl mmap \
           --split 949,50,1 \
           --distributed-backend nccl \
           --lr 0.00015 \
           --lr-decay-style cosine \
           --min-lr 1.0e-5 \
           --weight-decay 1e-2 \
           --clip-grad 1.0 \
           --lr-warmup-fraction .01 \
           --checkpoint-activations \
           --log-interval 10 \
           --save-interval 500 \
           --eval-interval 100 \
           --eval-iters 10 \
           --fp16

    The following figure shows the GPU usage.

    Figure 7 GPU usage

Step4 Using the GPT-2 Model to Generate Text

  1. Generate text automatically.

    1. Create a text generation script.
      vim generate_text.sh

      Add the following content:

      #!/bin/bash
      
      CHECKPOINT_PATH=checkpoints/gpt2
      VOCAB_FILE=data/gpt2-vocab.json
      MERGE_FILE=data/gpt2-merges.txt
      
      python tools/generate_samples_gpt.py \
             --tensor-model-parallel-size 1 \
             --num-layers 24 \
             --hidden-size 1024 \
             --load $CHECKPOINT_PATH \
             --num-attention-heads 16 \
             --max-position-embeddings 1024 \
             --tokenizer-type GPT2BPETokenizer \
             --fp16 \
             --micro-batch-size 2 \
             --seq-length 1024 \
             --out-seq-length 1024 \
             --temperature 1.0 \
             --vocab-file $VOCAB_FILE \
             --merge-file $MERGE_FILE \
             --genfile unconditional_samples.json \
             --num-samples 2 \
             --top_p 0.9 \
             --recompute
    2. Generate text.
      sh ./generate_text.sh

      If the following information is displayed, the text is generated.

      Figure 8 Text generated
    3. View the generated text.
      cat unconditional_samples.json

      The following figure shows the output.

      Figure 9 File information

  2. Enable interactive dialog.

    1. Create a text generation script.
      vim interactive_text.sh

      Enter the following information:

      #!/bin/bash
      
      CHECKPOINT_PATH=/workspace/Megatron-DeepSpeed/checkpoints/gpt2_345m
      VOCAB_FILE=/workspace/Megatron-DeepSpeed/data/gpt2-vocab.json
      MERGE_FILE=/workspace/Megatron-DeepSpeed/data/gpt2-merges.txt
      
      deepspeed /workspace/Megatron-DeepSpeed/tools/generate_samples_gpt.py \
             --tensor-model-parallel-size 1 \
             --num-layers 24 \
             --hidden-size 1024 \
             --load $CHECKPOINT_PATH \
             --num-attention-heads 16 \
             --max-position-embeddings 1024 \
             --tokenizer-type GPT2BPETokenizer \
             --fp16 \
             --micro-batch-size 2 \
             --seq-length 1024 \
             --out-seq-length 1024 \
             --temperature 1.0 \
             --vocab-file $VOCAB_FILE \
             --merge-file $MERGE_FILE \
             --genfile unconditional_samples.json \
             --num-samples 0 \
             --top_p 0.9 \
             --recompute
    2. Start interactive dialog.
      bash interactive_text.sh

      The following information is displayed. Enter huawei and press Enter.

      Context prompt (stop to exit) >>> huawei

      The text is automatically generated. The output depends on the model training and dataset.

      Figure 10 Model output