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
- Install the Megatron-DeepSpeed framework.
- Log in to the GPU BMS using SSH as user root.
- Pull the PyTorch image. You can download a common image source.
docker pull nvcr.io/nvidia/pytorch:21.10-py3
- 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
- Access the container terminal.
docker exec -it megatron-deepspeed bash
- 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.
- 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
- 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"
- Download and preprocess the dataset.
The OSCAR dataset in JSON format with 1 GB 79K-record is used.
- 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
- Decompress the dataset.
xz -d oscar-1GB.jsonl.xz
- 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
- Complete the preprocessing.
Figure 2 Data preprocessed
- Create the data directory and move the processed data.
mkdir data mv meg-gpt2* ./data mv gpt2* ./data
- Download the dataset.
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.
- Create the pre-training script file.
- Create the script.
vim pretrain_gpt2.sh
- 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
- Create the script.
- 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
- Start the pre-training.
nohup sh ./pretrain_gpt2.sh &
Figure 3 Starting pre-training
- 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
- Start the pre-training.
- 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.
- Currently, eight GPUs are selected for BMS. Adjust the parameters.
GPUS_PER_NODE=8
- 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
- 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
- Generate text automatically.
- 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
- Generate text.
sh ./generate_text.sh
If the following information is displayed, the text is generated.
Figure 8 Text generated
- View the generated text.
cat unconditional_samples.json
The following figure shows the output.
Figure 9 File information
- Create a text generation script.
- Enable interactive dialog.
- 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
- 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
- Create a text generation script.
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot