diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_config_gpt_TEMPLATE.json b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_config_gpt_TEMPLATE.json new file mode 100644 index 0000000000000000000000000000000000000000..295d11ccd7a4742c1e9f297451266f5eb156ce85 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_config_gpt_TEMPLATE.json @@ -0,0 +1,39 @@ +{ + "train_batch_size" : CONFIG_BATCH_SIZE, + "train_micro_batch_size_per_gpu": CONFIG_MBSIZE, + "steps_per_print": LOG_INTERVAL, + + "zero_optimization": { + "stage": ZERO_STAGE, + "elastic_checkpoint": true + }, + + "gradient_clipping": 1.0, + "prescale_gradients": PRESCALE_GRAD, + + "fp16": { + "enabled": CONFIG_FP16_ENABLED, + "loss_scale": 0, + "loss_scale_window": 500, + "hysteresis": 2, + "min_loss_scale": 1, + "initial_scale_power": 11 + }, + + "bf16": { + "enabled": CONFIG_BF16_ENABLED + }, + "curriculum_learning": { + "enabled": CONFIG_CL_ENABLED, + "curriculum_type": "seqlen", + "min_difficulty": CONFIG_CL_MIN, + "max_difficulty": CONFIG_CL_MAX, + "schedule_type": "fixed_linear", + "schedule_config": { + "total_curriculum_step": CONFIG_CL_DURATION, + "difficulty_step": 8 + } + }, + + "wall_clock_breakdown" : false +} diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_config_gpt_Zero2_TEMPLATE.json b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_config_gpt_Zero2_TEMPLATE.json new file mode 100644 index 0000000000000000000000000000000000000000..4d0a68f72deb3930c85adb69f37b331a706f6b22 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_config_gpt_Zero2_TEMPLATE.json @@ -0,0 +1,38 @@ +{ + "train_batch_size" : CONFIG_BATCH_SIZE, + "train_micro_batch_size_per_gpu": CONFIG_MBSIZE, + "steps_per_print": LOG_INTERVAL, + + "zero_optimization": { + "stage": 2 + }, + + "gradient_clipping": 1.0, + "prescale_gradients": false, + + "fp16": { + "enabled": CONFIG_FP16_ENABLED, + "loss_scale": 0, + "loss_scale_window": 500, + "hysteresis": 2, + "min_loss_scale": 1, + "initial_scale_power": 11 + }, + + "bf16": { + "enabled": CONFIG_BF16_ENABLED + }, + "curriculum_learning": { + "enabled": CONFIG_CL_ENABLED, + "curriculum_type": "seqlen", + "min_difficulty": CONFIG_CL_MIN, + "max_difficulty": CONFIG_CL_MAX, + "schedule_type": "fixed_linear", + "schedule_config": { + "total_curriculum_step": CONFIG_CL_DURATION, + "difficulty_step": 8 + } + }, + + "wall_clock_breakdown" : false +} diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_evalharness.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_evalharness.sh new file mode 100644 index 0000000000000000000000000000000000000000..f989b1f3700e28df14fef6fb4b1691ea7bada134 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_evalharness.sh @@ -0,0 +1,71 @@ +# This is an example zero-shot eval script. Please first read the readme_evalharness.md under the same directory. + +CHECKPOINT_PATH=/blob/users/conglli/project/gpt3_with_pile/checkpoint/gpt3-with-pile-0.125B-lr-2.4e-3-minlr-6.0e-5-bs-2048-gpus-128-zero-0-mp-1-pp-1-no_pp-cl-startseqlen-72-step-20728-token-45B/global_step81566/ +CONFIG_PATH=ds_config_gpt3-with-pile-0.125B-lr-2.4e-3-minlr-6.0e-5-bs-2048-gpus-128-zero-0-mp-1-pp-1-no_pp-cl-startseqlen-72-step-20728-token-45B.json +RESULT_PATH=gpt3-with-pile-0.125B-lr-2.4e-3-minlr-6.0e-5-bs-2048-gpus-128-zero-0-mp-1-pp-1-no_pp-cl-startseqlen-72-step-20728-token-45B_global_step81566.log + +PP_SIZE=1 +TP_SIZE=1 +NO_PP="true" +EP_PARALLEL_SIZE=1 +# Currently eval harness does not support data parallel +# However, for MoE models it's possible to enable a "fake data parallel" +# in order to load experts on multiple gpus. At the same time, it's not +# real data parallel because we load the same data on all gpus. +# On the other hand, it's better to use less number of gpus than training, +# to reduce communication overhead. +NUM_NODE=1 +NUM_GPU_PER_NODE=1 + +TASKS="lambada" +# WikiText-2, not used in GPT-3 paper but used in GPT-2 paper +# TASKS="wikitext" +# Tasks that appeared in GPT-3 paper (sorted based on the order in paper), plus WikiText-2. +# TASKS="hellaswag,lambada,triviaqa,webqs,winogrande,piqa,arc_challenge,arc_easy,openbookqa,race,boolq,cb,copa,rte,wic,wsc,multirc,record,anli_r1,anli_r2,anli_r3,wikitext" +# All tasks that confirmed to work, there are more tasks on https://github.com/EleutherAI/lm-evaluation-harness that we didn't test. +# TASKS="hellaswag,lambada,triviaqa,webqs,winogrande,piqa,arc_challenge,arc_easy,openbookqa,race,boolq,cb,copa,rte,wic,wsc,multirc,record,anli_r1,anli_r2,anli_r3,wikitext,logiqa,mathqa,mc_taco,mrpc,prost,pubmedqa,qnli,qqp,sciq,sst,wnli" + +VOCAB_FILE=/data/Megatron-LM/data/gpt2-vocab.json +MERGE_FILE=/data/Megatron-LM/data/gpt2-merges.txt + +export HF_DATASETS_OFFLINE=1 + +# Dummy arguments to make megatron happy. No need to configure them. +# The reason we don't need to configure them and many other arguments is +# because the eval framework will read the arguments from checkpoint file. +MEGATRON_REQUIRED_ARGS="\ + --num-layers -1\ + --hidden-size -1\ + --num-attention-heads -1\ + --seq-length -1 \ + --max-position-embeddings -1 +" + +CMD="../../tasks/eval_harness/evaluate.py \ + --load $CHECKPOINT_PATH\ + --tensor-model-parallel-size $TP_SIZE \ + --pipeline-model-parallel-size $PP_SIZE\ + --moe-expert-parallel-size ${EP_PARALLEL_SIZE} \ + --vocab-file $VOCAB_FILE\ + --merge-file $MERGE_FILE\ + --micro-batch-size 12\ + --no-load-optim \ + --no-load-rng \ + --inference \ + --disable-moe-token-dropping \ + --adaptive_seq_len\ + --eval_fp32\ + --task_list $TASKS\ + --results_path $RESULT_PATH \ + --deepspeed \ + --deepspeed_config $CONFIG_PATH \ + $MEGATRON_REQUIRED_ARGS\ + " + +if [[ "${NO_PP}" = "true" ]]; then +CMD="${CMD} \ + --no-pipeline-parallel" +fi + +LAUNCHER="deepspeed --num_nodes $NUM_NODE --num_gpus $NUM_GPU_PER_NODE" +$LAUNCHER $CMD \ No newline at end of file diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_1.3B_MoE128.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_1.3B_MoE128.sh new file mode 100644 index 0000000000000000000000000000000000000000..30a7b5f3e1508cacef79f382fff007f2840553a7 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_1.3B_MoE128.sh @@ -0,0 +1,349 @@ +#!/bin/bash +DIR=`pwd` +############################################################################### +### Main configs +## GPT-3 models use 2K sequence length/context window +SEQ_LEN=2048 + +### The "GPT-3 XXX" below are configs from GPT-3 paper +### https://arxiv.org/abs/2005.14165, choose based on +### your desired model size or build your own configs + +## GPT-3 Small 125M +# MODEL_SIZE=0.125 +# NUM_LAYERS=12 +# HIDDEN_SIZE=768 +# NUM_ATTN_HEADS=12 +# GLOBAL_BATCH_SIZE=256 +# LR=6.0e-4 +# MIN_LR=6.0e-5 + +## GPT-3 Medium 350M +# MODEL_SIZE=0.35 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1024 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=3.0e-4 +# MIN_LR=3.0e-5 + +## GPT-3 Large 760M +# MODEL_SIZE=0.76 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1536 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=2.5e-4 +# MIN_LR=2.5e-5 + +## GPT-3 XL 1.3B +MODEL_SIZE=1.3 +NUM_LAYERS=24 +HIDDEN_SIZE=2048 +NUM_ATTN_HEADS=16 +GLOBAL_BATCH_SIZE=512 +# LR=2.0e-4 +# MIN_LR=2.0e-5 + +## GPT-3 2.7B +# MODEL_SIZE=2.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=2560 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=512 +# LR=1.6e-4 +# MIN_LR=1.6e-5 + +## GPT-3 6.7B +# MODEL_SIZE=6.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=4096 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.2e-4 +# MIN_LR=1.2e-5 + +## GPT-3 13B +# MODEL_SIZE=13 +# NUM_LAYERS=40 +# HIDDEN_SIZE=5120 +# NUM_ATTN_HEADS=40 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.0e-4 +# MIN_LR=1.0e-5 + +## GPT-3 175B +# MODEL_SIZE=175 +# NUM_LAYERS=96 +# HIDDEN_SIZE=12288 +# NUM_ATTN_HEADS=96 +# GLOBAL_BATCH_SIZE=1536 +# LR=0.6e-4 +# MIN_LR=0.6e-5 +############################################################################### +### Training duration configs +## The main termination condition, original GPT-3 paper trains for 300B tokens +## For MoE model, we found sometimes training a bit more to 330B tokens helps +TRAIN_TOKENS=300000000000 +# TRAIN_TOKENS=330000000000 + +## TRAIN_ITERS is another termination condition and also affect the number of +## data samples to be indexed. Since we want to reach the TRAIN_TOKENS +## above, and techniques like curriculum learning has less token in some steps, +## so we just set this config large enough to make sure we have enough +## processed data and don't terminate by TRAIN_ITERS. +TRAIN_ITERS=$(( ${TRAIN_TOKENS} * 3 / ${GLOBAL_BATCH_SIZE} / ${SEQ_LEN} )) + +## Another termination condition in minutes. Set it large enough to avoid +## undesired early termination. +EXIT_DURATION=30000000 +############################################################################### +### LR configs +## LR warmup and decay duration, this token-based config is preferable since +## no need to readjust when the batch size/seqlen is changed. +## Original GPT-3 paper uses 375M warmup tokens and 260B decay tokens. +## For MoE model, we found that setting the decay token to 300B helps. +WARMUP_TOKENS=375000000 +# LR_DECAY_TOKENS=260000000000 +LR_DECAY_TOKENS=300000000000 +############################################################################### +### Parallelism configs +## Micro batch size per GPU +## Make sure that BATCH_SIZE <= GLOBAL_BATCH_SIZE*PP_SIZE*MP_SIZE/NUM_GPUS +BATCH_SIZE=8 + +## Model parallelism, 1 is no MP +## Currently MoE models have divergence issue when MP > 1. +MP_SIZE=1 + +## Pipeline parallelism +## Currently we don't support PP for MoE. To disable PP, set PP_SIZE +## to 1 and use the "--no-pipeline-parallel" arg. +PP_SIZE=1 +NUM_GPUS=64 +############################################################################### +### MoE configs +## Number of experts. EP_SIZE 1 means dense model without MoE +# EP_SIZE=1 +EP_SIZE=128 + +if [[ $EP_SIZE -gt $NUM_GPUS ]]; then + EP_PARALLEL_SIZE=$NUM_GPUS +else + EP_PARALLEL_SIZE=$EP_SIZE +fi + +## Original GPT-3 model always set min LR at 10% of max LR. For MoE model, we +## found that lower LR and min LR (than the base dense model) helps. +## For 1.3B MoE-128 model we used LR=1.2e-4 and MIN_LR=1.0e-6. +## For 350M MoE-128 model we used LR=2.0e-4 and MIN_LR=2.0e-6, but they are not +## heavily tuned. +LR=1.2e-4 +MIN_LR=1.0e-6 + +## Coefficient for MoE loss. We find that 0.01 is a good value at least for +## 1.3B MoE-128 model +MLC=0.01 + +## Below configs adjust the MoE expert token capacity limit during training and +## eval. To completely disable capacity limit, set MOE_DROP_TOKEN to false. +## Larger capacity factor or disabling capacity limit could improve training +## convergence, but will also reduce training throughput. +MOE_TRAIN_CAP_FACTOR=1.0 +MOE_EVAL_CAP_FACTOR=1.0 +MOE_MIN_CAP=4 +MOE_DROP_TOKEN="true" +# MOE_DROP_TOKEN="false" +############################################################################### +### Curriculum learning (CL) configs +## Enable/disable CL +CL_ENABLED="false" +## Consult the tutorial https://www.deepspeed.ai/tutorials/curriculum-learning/ +## for tuning the following configs +CL_START_SEQLEN=80 +CL_AVG_SEQLEN=$(( (${CL_START_SEQLEN} + ${SEQ_LEN}) / 2 )) +CL_TOKENS=60 +CL_TOKENS=$((${CL_TOKENS} * 1000000000)) +CL_STEP=$(( ${CL_TOKENS} / (${GLOBAL_BATCH_SIZE} * ${CL_AVG_SEQLEN}) )) +############################################################################### +### Misc configs +LOG_INTERVAL=10 +EVAL_ITERS=10 +EVAL_INTERVAL=100 +SAVE_INTERVAL=10000 + +## Standard deviation for weight initialization +## We used 0.014 for 350M/1.3B dense/MoE models, and used 0.01 for 6.7B +## dense model. Usually larger model needs lower std. +INIT_STD=0.014 +# INIT_STD=0.01 + +## Activation checkpointing saves GPU memory, but reduces training speed +ACTIVATION_CHECKPOINT="true" +# ACTIVATION_CHECKPOINT="false" +############################################################################### +### Output and data configs +current_time=$(date "+%Y.%m.%d-%H.%M.%S") +host="${HOSTNAME}" +NAME="gpt-${MODEL_SIZE}B-lr-${LR}-minlr-${MIN_LR}-bs-${GLOBAL_BATCH_SIZE}-gpus-${NUM_GPUS}-mp-${MP_SIZE}-pp-${PP_SIZE}" +if [[ $EP_SIZE -gt 1 ]]; then + NAME="${NAME}-ep-${EP_SIZE}-mlc-${MLC}-cap-${MOE_TRAIN_CAP_FACTOR}-drop-${MOE_DROP_TOKEN}" +fi +if [ "${CL_ENABLED}" = "true" ]; then + NAME="${NAME}-cl-${CL_START_SEQLEN}-${CL_STEP}" +fi + +OUTPUT_BASEPATH=$DIR/output +mkdir -p "${OUTPUT_BASEPATH}/tensorboard/" +mkdir -p "${OUTPUT_BASEPATH}/checkpoint/" +mkdir -p "${OUTPUT_BASEPATH}/log/" +TENSORBOARD_DIR="${OUTPUT_BASEPATH}/tensorboard/${NAME}_${host}_${current_time}" +mkdir -p ${TENSORBOARD_DIR} +## Note that for MoE model with billion-scale base model, the checkpoint can be +## as large as TB-scale which normal NFS cannot handle efficiently. +CHECKPOINT_PATH="${OUTPUT_BASEPATH}/checkpoint/${NAME}" + +# USE_INTERNAL_DATA="true" +USE_INTERNAL_DATA="false" + +if [ "${USE_INTERNAL_DATA}" = "true" ]; then + ## The internal data is only accessible within Microsoft + ## For cluster Azure-EastUS-V100-32GB-4, Azure-WestUS3-A100 + # BASE_DATA_PATH=/vc_data/Megatron-LM/data + # DATA_HOME="/vc_data/pile-cc1-cc2-shuf" + ## For cluster Lab-RR1-V100 + BASE_DATA_PATH=/data/Megatron-LM/data + DATA_HOME="/turing-ssd/users/conglli/data/pile-cc1-cc2-shuf" + ## For cluster Azure-CentralUS-A100 + # BASE_DATA_PATH=/data/Megatron-LM/data + # DATA_HOME=/vc_data_1/users/amawa/blended + + VOCAB_PATH=${BASE_DATA_PATH}/gpt2-vocab.json + MERGE_PATH=${BASE_DATA_PATH}/gpt2-merges.txt + ARX="${DATA_HOME}/ArXiv_ftfy_cleaned_id_shuf_text_document" + BC2="${DATA_HOME}/BookCorpus2_ftfy_cleaned_id_shuf_text_document" + B3="${DATA_HOME}/Books3_ftfy_cleaned_id_shuf_text_document" + CC2020="${DATA_HOME}/CC-2020-50_id_cleaned_shuf_text_document" + CC2021="${DATA_HOME}/CC-2021-04_id_cleaned_shuf_text_document" + GIT="${DATA_HOME}/Github_ftfy_id_shuf_text_document" + GUT="${DATA_HOME}/Gutenberg_PG-19_ftfy_cleaned_id_cleaned_shuf_text_document" + NIH="${DATA_HOME}/NIH_ExPorter_ftfy_id_shuf_text_document" + OWT2="${DATA_HOME}/OpenWebText2_ftfy_cleaned_id_shuf_text_document" + PCC="${DATA_HOME}/Pile-CC_id_cleaned_shuf_text_document" + PM="${DATA_HOME}/PubMed_Abstracts_ftfy_id_shuf_text_document" + RN="${DATA_HOME}/rn_dedup_shuf_cleaned_0.7_cleaned_shuf_text_document" + SE="${DATA_HOME}/StackExchange_ftfy_id_shuf_text_document" + ST="${DATA_HOME}/stories_dedup0.7_shuf_cleaned_shuf_text_document" + WIK="${DATA_HOME}/Wikipedia_en_ftfy_id_shuf_text_document" + DATA_BLEND="0.14336 ${B3} 0.08962 ${RN} 0.19336 ${OWT2} 0.05689 ${SE} \ + 0.00859 ${ST} 0.02897 ${PM} 0.04771 ${WIK} 0.00873 ${GUT} 0.01007 ${BC2} \ + 0.00208 ${NIH} 0.13017 ${CC2020} 0.09446 ${PCC} 0.15652 ${CC2021} \ + 0.01359 ${ARX} 0.01588 ${GIT}" +else + VOCAB_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-vocab.json + MERGE_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-merges.txt + # Public the Pile dataset, can be downloaded at https://mystic.the-eye.eu/public/AI/pile_neox/ + DATA_BLEND=/data/the_pile_public_merged_nopreprocessing/pile_text_document +fi +############################################################################### +data_options=" \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --data-path ${DATA_BLEND} \ + --data-impl mmap" + +megatron_options=" \ + --override-lr-scheduler \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --tensor-model-parallel-size ${MP_SIZE} \ + --moe-expert-parallel-size ${EP_PARALLEL_SIZE} \ + --num-experts ${EP_SIZE} \ + --moe-loss-coeff ${MLC} \ + --moe-train-capacity-factor ${MOE_TRAIN_CAP_FACTOR} \ + --moe-eval-capacity-factor ${MOE_EVAL_CAP_FACTOR} \ + --moe-min-capacity ${MOE_MIN_CAP} \ + --init-method-std ${INIT_STD} \ + --lr-decay-tokens ${LR_DECAY_TOKENS} \ + --lr-warmup-tokens ${WARMUP_TOKENS} \ + --micro-batch-size ${BATCH_SIZE} \ + --exit-duration-in-mins ${EXIT_DURATION} \ + --global-batch-size ${GLOBAL_BATCH_SIZE} \ + --num-layers ${NUM_LAYERS} \ + --hidden-size ${HIDDEN_SIZE} \ + --num-attention-heads ${NUM_ATTN_HEADS} \ + --seq-length ${SEQ_LEN} \ + --max-position-embeddings ${SEQ_LEN} \ + --train-tokens ${TRAIN_TOKENS} \ + --train-iters ${TRAIN_ITERS} \ + --lr ${LR} \ + --min-lr ${MIN_LR} \ + --lr-decay-style cosine \ + --split 98,2,0 \ + --log-interval ${LOG_INTERVAL} \ + --eval-interval ${EVAL_INTERVAL} \ + --eval-iters ${EVAL_ITERS} \ + --save-interval ${SAVE_INTERVAL} \ + --weight-decay 0.1 \ + --clip-grad 1.0 \ + --hysteresis 2 \ + --num-workers 0 \ + --fp16 \ + --load ${CHECKPOINT_PATH} \ + --save ${CHECKPOINT_PATH} \ + --tensorboard-queue-size 1 \ + --log-timers-to-tensorboard \ + --log-batch-size-to-tensorboard \ + --log-validation-ppl-to-tensorboard \ + --tensorboard-dir ${TENSORBOARD_DIR}" + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +megatron_options="${megatron_options} \ + --checkpoint-activations" +fi + +if [[ $EP_SIZE -gt 1 ]]; then +megatron_options="${megatron_options} \ + --create-moe-param-group" +fi + +if [ "${MOE_DROP_TOKEN}" = "false" ]; then +megatron_options="${megatron_options} \ + --disable-moe-token-dropping" +fi + +template_json="ds_config_gpt_TEMPLATE.json" +config_json="ds_config_gpt_${NAME}.json" +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/ZERO_STAGE/0/" \ + | sed "s/PRESCALE_GRAD/true/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} + +deepspeed_options=" \ + --deepspeed \ + --deepspeed_config ${config_json} \ + --pipeline-model-parallel-size ${PP_SIZE}" + +# Currently MoE is not compatible with pipeline parallel +if [[ $EP_SIZE -gt 1 ]]; then +deepspeed_options="${deepspeed_options} \ + --no-pipeline-parallel" +fi + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +deepspeed_options="${deepspeed_options} \ + --deepspeed-activation-checkpointing" +fi + +run_cmd="deepspeed ${DIR}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &> ${OUTPUT_BASEPATH}/log/${NAME}_${host}_${current_time}.log" +echo ${run_cmd} +eval ${run_cmd} +set +x diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_1.3B_PR-MoE64or128.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_1.3B_PR-MoE64or128.sh new file mode 100644 index 0000000000000000000000000000000000000000..907f0fe579c7a61bc2954c9b8882d4054b81b2f7 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_1.3B_PR-MoE64or128.sh @@ -0,0 +1,341 @@ +#!/bin/bash +DIR=`pwd` +############################################################################### +### Main configs +## GPT-3 models use 2K sequence length/context window +SEQ_LEN=2048 + +### The "GPT-3 XXX" below are configs from GPT-3 paper +### https://arxiv.org/abs/2005.14165, choose based on +### your desired model size or build your own configs + +## GPT-3 Small 125M +# MODEL_SIZE=0.125 +# NUM_LAYERS=12 +# HIDDEN_SIZE=768 +# NUM_ATTN_HEADS=12 +# GLOBAL_BATCH_SIZE=256 +# LR=6.0e-4 +# MIN_LR=6.0e-5 + +## GPT-3 Medium 350M +# MODEL_SIZE=0.35 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1024 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=3.0e-4 +# MIN_LR=3.0e-5 + +## GPT-3 Large 760M +# MODEL_SIZE=0.76 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1536 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=2.5e-4 +# MIN_LR=2.5e-5 + +## GPT-3 XL 1.3B +MODEL_SIZE=1.3 +NUM_LAYERS=24 +HIDDEN_SIZE=2048 +NUM_ATTN_HEADS=16 +GLOBAL_BATCH_SIZE=512 +# LR=2.0e-4 +# MIN_LR=2.0e-5 + +## GPT-3 2.7B +# MODEL_SIZE=2.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=2560 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=512 +# LR=1.6e-4 +# MIN_LR=1.6e-5 + +## GPT-3 6.7B +# MODEL_SIZE=6.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=4096 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.2e-4 +# MIN_LR=1.2e-5 + +## GPT-3 13B +# MODEL_SIZE=13 +# NUM_LAYERS=40 +# HIDDEN_SIZE=5120 +# NUM_ATTN_HEADS=40 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.0e-4 +# MIN_LR=1.0e-5 + +## GPT-3 175B +# MODEL_SIZE=175 +# NUM_LAYERS=96 +# HIDDEN_SIZE=12288 +# NUM_ATTN_HEADS=96 +# GLOBAL_BATCH_SIZE=1536 +# LR=0.6e-4 +# MIN_LR=0.6e-5 +############################################################################### +### Training duration configs +## The main termination condition, original GPT-3 paper trains for 300B tokens +## For MoE model, we found sometimes training a bit more to 330B tokens helps +TRAIN_TOKENS=300000000000 +# TRAIN_TOKENS=330000000000 + +## TRAIN_ITERS is another termination condition and also affect the number of +## data samples to be indexed. Since we want to reach the TRAIN_TOKENS +## above, and techniques like curriculum learning has less token in some steps, +## so we just set this config large enough to make sure we have enough +## processed data and don't terminate by TRAIN_ITERS. +TRAIN_ITERS=$(( ${TRAIN_TOKENS} * 3 / ${GLOBAL_BATCH_SIZE} / ${SEQ_LEN} )) + +## Another termination condition in minutes. Set it large enough to avoid +## undesired early termination. +EXIT_DURATION=30000000 +############################################################################### +### LR configs +## LR warmup and decay duration, this token-based config is preferable since +## no need to readjust when the batch size/seqlen is changed. +## Original GPT-3 paper uses 375M warmup tokens and 260B decay tokens. +## For MoE model, we found that setting the decay token to 300B helps. +WARMUP_TOKENS=375000000 +# LR_DECAY_TOKENS=260000000000 +LR_DECAY_TOKENS=300000000000 +############################################################################### +### Parallelism configs +## Micro batch size per GPU +## Make sure that BATCH_SIZE <= GLOBAL_BATCH_SIZE*PP_SIZE*MP_SIZE/NUM_GPUS +BATCH_SIZE=8 + +## Model parallelism, 1 is no MP +## Currently MoE models have divergence issue when MP > 1. +MP_SIZE=1 + +## Pipeline parallelism +## Currently we don't support PP for MoE. To disable PP, set PP_SIZE +## to 1 and use the "--no-pipeline-parallel" arg. +PP_SIZE=1 +NUM_GPUS=64 +############################################################################### +### MoE configs +## Number of experts. EP_SIZE 128 means standard MoE +# EP_SIZE=128 +EP_SIZE="64 64 64 64 64 64 64 64 64 64 128 128" + + +EP_PARALLEL_SIZE=$NUM_GPUS + + +## Original GPT-3 model always set min LR at 10% of max LR. For MoE model, we +## found that lower LR and min LR (than the base dense model) helps. +## For 1.3B PR-MoE-64/128 model we used LR=1.2e-4 and MIN_LR=1.0e-6. +## heavily tuned. +LR=1.2e-4 +MIN_LR=1.0e-6 + +## Coefficient for MoE loss. We find that 0.01 is a good value at least for +## 1.3B MoE-128 model +MLC=0.01 + +## Below configs adjust the MoE expert token capacity limit during training and +## eval. To completely disable capacity limit, set MOE_DROP_TOKEN to false. +## Larger capacity factor or disabling capacity limit could improve training +## convergence, but will also reduce training throughput. +MOE_TRAIN_CAP_FACTOR=1.0 +MOE_EVAL_CAP_FACTOR=1.0 +MOE_MIN_CAP=4 +MOE_DROP_TOKEN="true" +# MOE_DROP_TOKEN="false" +############################################################################### +### Curriculum learning (CL) configs +## Enable/disable CL +CL_ENABLED="false" +## Consult the tutorial https://www.deepspeed.ai/tutorials/curriculum-learning/ +## for tuning the following configs +CL_START_SEQLEN=80 +CL_AVG_SEQLEN=$(( (${CL_START_SEQLEN} + ${SEQ_LEN}) / 2 )) +CL_TOKENS=60 +CL_TOKENS=$((${CL_TOKENS} * 1000000000)) +CL_STEP=$(( ${CL_TOKENS} / (${GLOBAL_BATCH_SIZE} * ${CL_AVG_SEQLEN}) )) +############################################################################### +### Misc configs +LOG_INTERVAL=10 +EVAL_ITERS=10 +EVAL_INTERVAL=100 +SAVE_INTERVAL=10000 + +## Standard deviation for weight initialization +## We used 0.014 for 350M/1.3B dense/MoE models, and used 0.01 for 6.7B +## dense model. Usually larger model needs lower std. +INIT_STD=0.014 +# INIT_STD=0.01 + +## Activation checkpointing saves GPU memory, but reduces training speed +ACTIVATION_CHECKPOINT="true" +# ACTIVATION_CHECKPOINT="false" +############################################################################### +### Output and data configs +current_time=$(date "+%Y.%m.%d-%H.%M.%S") +host="${HOSTNAME}" +NAME="gpt-${MODEL_SIZE}B-lr-${LR}-minlr-${MIN_LR}-bs-${GLOBAL_BATCH_SIZE}-gpus-${NUM_GPUS}-mp-${MP_SIZE}-pp-${PP_SIZE}" +NAME="${NAME}-ep-pyramid-64+128-mlc-${MLC}-cap-${MOE_TRAIN_CAP_FACTOR}-drop-${MOE_DROP_TOKEN}" + +if [ "${CL_ENABLED}" = "true" ]; then + NAME="${NAME}-cl-${CL_START_SEQLEN}-${CL_STEP}" +fi + +OUTPUT_BASEPATH=$DIR/output +mkdir -p "${OUTPUT_BASEPATH}/tensorboard/" +mkdir -p "${OUTPUT_BASEPATH}/checkpoint/" +mkdir -p "${OUTPUT_BASEPATH}/log/" +TENSORBOARD_DIR="${OUTPUT_BASEPATH}/tensorboard/${NAME}_${host}_${current_time}" +mkdir -p ${TENSORBOARD_DIR} +## Note that for MoE model with billion-scale base model, the checkpoint can be +## as large as TB-scale which normal NFS cannot handle efficiently. +CHECKPOINT_PATH="${OUTPUT_BASEPATH}/checkpoint/${NAME}" + +# USE_INTERNAL_DATA="true" +USE_INTERNAL_DATA="false" + +if [ "${USE_INTERNAL_DATA}" = "true" ]; then + ## The internal data is only accessible within Microsoft + ## For cluster Azure-EastUS-V100-32GB-4, Azure-WestUS3-A100 + BASE_DATA_PATH=/vc_data/Megatron-LM/data + DATA_HOME="/vc_data/pile-cc1-cc2-shuf" + ## For cluster Lab-RR1-V100 + # BASE_DATA_PATH=/data/Megatron-LM/data + # DATA_HOME="/turing-ssd/users/conglli/data/pile-cc1-cc2-shuf" + ## For cluster Azure-CentralUS-A100 + # BASE_DATA_PATH=/data/Megatron-LM/data + # DATA_HOME=/vc_data_1/users/amawa/blended + + VOCAB_PATH=${BASE_DATA_PATH}/gpt2-vocab.json + MERGE_PATH=${BASE_DATA_PATH}/gpt2-merges.txt + ARX="${DATA_HOME}/ArXiv_ftfy_cleaned_id_shuf_text_document" + BC2="${DATA_HOME}/BookCorpus2_ftfy_cleaned_id_shuf_text_document" + B3="${DATA_HOME}/Books3_ftfy_cleaned_id_shuf_text_document" + CC2020="${DATA_HOME}/CC-2020-50_id_cleaned_shuf_text_document" + CC2021="${DATA_HOME}/CC-2021-04_id_cleaned_shuf_text_document" + GIT="${DATA_HOME}/Github_ftfy_id_shuf_text_document" + GUT="${DATA_HOME}/Gutenberg_PG-19_ftfy_cleaned_id_cleaned_shuf_text_document" + NIH="${DATA_HOME}/NIH_ExPorter_ftfy_id_shuf_text_document" + OWT2="${DATA_HOME}/OpenWebText2_ftfy_cleaned_id_shuf_text_document" + PCC="${DATA_HOME}/Pile-CC_id_cleaned_shuf_text_document" + PM="${DATA_HOME}/PubMed_Abstracts_ftfy_id_shuf_text_document" + RN="${DATA_HOME}/rn_dedup_shuf_cleaned_0.7_cleaned_shuf_text_document" + SE="${DATA_HOME}/StackExchange_ftfy_id_shuf_text_document" + ST="${DATA_HOME}/stories_dedup0.7_shuf_cleaned_shuf_text_document" + WIK="${DATA_HOME}/Wikipedia_en_ftfy_id_shuf_text_document" + DATA_BLEND="0.14336 ${B3} 0.08962 ${RN} 0.19336 ${OWT2} 0.05689 ${SE} \ + 0.00859 ${ST} 0.02897 ${PM} 0.04771 ${WIK} 0.00873 ${GUT} 0.01007 ${BC2} \ + 0.00208 ${NIH} 0.13017 ${CC2020} 0.09446 ${PCC} 0.15652 ${CC2021} \ + 0.01359 ${ARX} 0.01588 ${GIT}" +else + VOCAB_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-vocab.json + MERGE_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-merges.txt + # Public the Pile dataset, can be downloaded at https://mystic.the-eye.eu/public/AI/pile_neox/ + DATA_BLEND=/data/the_pile_public_merged_nopreprocessing/pile_text_document +fi +############################################################################### +data_options=" \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --data-path ${DATA_BLEND} \ + --data-impl mmap" + +megatron_options=" \ + --override-lr-scheduler \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --tensor-model-parallel-size ${MP_SIZE} \ + --moe-expert-parallel-size ${EP_PARALLEL_SIZE} \ + --num-experts ${EP_SIZE} \ + --moe-loss-coeff ${MLC} \ + --mlp-type residual \ + --moe-train-capacity-factor ${MOE_TRAIN_CAP_FACTOR} \ + --moe-eval-capacity-factor ${MOE_EVAL_CAP_FACTOR} \ + --moe-min-capacity ${MOE_MIN_CAP} \ + --init-method-std ${INIT_STD} \ + --lr-decay-tokens ${LR_DECAY_TOKENS} \ + --lr-warmup-tokens ${WARMUP_TOKENS} \ + --micro-batch-size ${BATCH_SIZE} \ + --exit-duration-in-mins ${EXIT_DURATION} \ + --global-batch-size ${GLOBAL_BATCH_SIZE} \ + --num-layers ${NUM_LAYERS} \ + --hidden-size ${HIDDEN_SIZE} \ + --num-attention-heads ${NUM_ATTN_HEADS} \ + --seq-length ${SEQ_LEN} \ + --max-position-embeddings ${SEQ_LEN} \ + --train-tokens ${TRAIN_TOKENS} \ + --train-iters ${TRAIN_ITERS} \ + --lr ${LR} \ + --min-lr ${MIN_LR} \ + --lr-decay-style cosine \ + --split 98,2,0 \ + --log-interval ${LOG_INTERVAL} \ + --eval-interval ${EVAL_INTERVAL} \ + --eval-iters ${EVAL_ITERS} \ + --save-interval ${SAVE_INTERVAL} \ + --weight-decay 0.1 \ + --clip-grad 1.0 \ + --hysteresis 2 \ + --num-workers 0 \ + --fp16 \ + --load ${CHECKPOINT_PATH} \ + --save ${CHECKPOINT_PATH} \ + --tensorboard-queue-size 1 \ + --log-timers-to-tensorboard \ + --log-batch-size-to-tensorboard \ + --log-validation-ppl-to-tensorboard \ + --tensorboard-dir ${TENSORBOARD_DIR}" + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +megatron_options="${megatron_options} \ + --checkpoint-activations" +fi + +megatron_options="${megatron_options} \ + --create-moe-param-group" + + +if [ "${MOE_DROP_TOKEN}" = "false" ]; then +megatron_options="${megatron_options} \ + --disable-moe-token-dropping" +fi + +template_json="ds_config_gpt_Zero2_TEMPLATE.json" +config_json="ds_config_gpt_${NAME}.json" +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} + +deepspeed_options=" \ + --deepspeed \ + --deepspeed_config ${config_json} \ + --pipeline-model-parallel-size ${PP_SIZE}" + +# Currently MoE is not compatible with pipeline parallel +deepspeed_options="${deepspeed_options} \ + --no-pipeline-parallel" + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +deepspeed_options="${deepspeed_options} \ + --deepspeed-activation-checkpointing" +fi + +run_cmd="deepspeed ${DIR}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &> ${OUTPUT_BASEPATH}/log/${NAME}_${host}_${current_time}.log" +echo ${run_cmd} +eval ${run_cmd} +set +x diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_1.3B_PR-MoE64or128_MoS.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_1.3B_PR-MoE64or128_MoS.sh new file mode 100644 index 0000000000000000000000000000000000000000..7b9583a880c2e1bae24dabb26da69f67768bfa54 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_1.3B_PR-MoE64or128_MoS.sh @@ -0,0 +1,355 @@ +#!/bin/bash +DIR=`pwd` +############################################################################### +### Main configs +## GPT-3 models use 2K sequence length/context window +SEQ_LEN=2048 + +### The "GPT-3 XXX" below are configs from GPT-3 paper +### https://arxiv.org/abs/2005.14165, choose based on +### your desired model size or build your own configs + +## GPT-3 Small 125M +# MODEL_SIZE=0.125 +# NUM_LAYERS=12 +# HIDDEN_SIZE=768 +# NUM_ATTN_HEADS=12 +# GLOBAL_BATCH_SIZE=256 +# LR=6.0e-4 +# MIN_LR=6.0e-5 + +## GPT-3 Medium 350M +# MODEL_SIZE=0.35 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1024 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=3.0e-4 +# MIN_LR=3.0e-5 + +## GPT-3 Large 760M +# MODEL_SIZE=0.76 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1536 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=2.5e-4 +# MIN_LR=2.5e-5 + +## GPT-3 XL 1.3B +MODEL_SIZE=1.3 +NUM_LAYERS=24 +HIDDEN_SIZE=2048 +NUM_ATTN_HEADS=16 +GLOBAL_BATCH_SIZE=512 +# LR=2.0e-4 +# MIN_LR=2.0e-5 + +## GPT-3 2.7B +# MODEL_SIZE=2.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=2560 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=512 +# LR=1.6e-4 +# MIN_LR=1.6e-5 + +## GPT-3 6.7B +# MODEL_SIZE=6.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=4096 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.2e-4 +# MIN_LR=1.2e-5 + +## GPT-3 13B +# MODEL_SIZE=13 +# NUM_LAYERS=40 +# HIDDEN_SIZE=5120 +# NUM_ATTN_HEADS=40 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.0e-4 +# MIN_LR=1.0e-5 + +## GPT-3 175B +# MODEL_SIZE=175 +# NUM_LAYERS=96 +# HIDDEN_SIZE=12288 +# NUM_ATTN_HEADS=96 +# GLOBAL_BATCH_SIZE=1536 +# LR=0.6e-4 +# MIN_LR=0.6e-5 +############################################################################### +### Training duration configs +## The main termination condition, original GPT-3 paper trains for 300B tokens +## For MoE model, we found sometimes training a bit more to 330B tokens helps +TRAIN_TOKENS=300000000000 +# TRAIN_TOKENS=330000000000 + +## TRAIN_ITERS is another termination condition and also affect the number of +## data samples to be indexed. Since we want to reach the TRAIN_TOKENS +## above, and techniques like curriculum learning has less token in some steps, +## so we just set this config large enough to make sure we have enough +## processed data and don't terminate by TRAIN_ITERS. +TRAIN_ITERS=$(( ${TRAIN_TOKENS} * 3 / ${GLOBAL_BATCH_SIZE} / ${SEQ_LEN} )) + +## Another termination condition in minutes. Set it large enough to avoid +## undesired early termination. +EXIT_DURATION=30000000 +############################################################################### +### LR configs +## LR warmup and decay duration, this token-based config is preferable since +## no need to readjust when the batch size/seqlen is changed. +## Original GPT-3 paper uses 375M warmup tokens and 260B decay tokens. +## For MoE model, we found that setting the decay token to 300B helps. +WARMUP_TOKENS=375000000 +# LR_DECAY_TOKENS=260000000000 +LR_DECAY_TOKENS=300000000000 +############################################################################### +### Parallelism configs +## Micro batch size per GPU +## Make sure that BATCH_SIZE <= GLOBAL_BATCH_SIZE*PP_SIZE*MP_SIZE/NUM_GPUS +BATCH_SIZE=4 + +## Model parallelism, 1 is no MP +## Currently MoE models have divergence issue when MP > 1. +MP_SIZE=1 + +## Pipeline parallelism +## Currently we don't support PP for MoE. To disable PP, set PP_SIZE +## to 1 and use the "--no-pipeline-parallel" arg. +PP_SIZE=1 +NUM_GPUS=128 +############################################################################### +### MoE configs +## Number of experts. EP_SIZE 128 means standard MoE +# EP_SIZE=128 +EP_SIZE="64 64 64 64 64 64 64 64 128 128" +EP_SIZE_TEACHER="64 64 64 64 64 64 64 64 64 64 128 128" + +EP_PARALLEL_SIZE=$NUM_GPUS + + +## Original GPT-3 model always set min LR at 10% of max LR. For MoE model, we +## found that lower LR and min LR (than the base dense model) helps. +## For 1.3B PR-MoE-64/128 model we used LR=1.2e-4 and MIN_LR=1.0e-6. +## heavily tuned. +LR=1.2e-4 +MIN_LR=1.0e-6 + +## Coefficient for MoE loss. We find that 0.01 is a good value at least for +## 1.3B MoE-128 model +MLC=0.01 + +## Below configs adjust the MoE expert token capacity limit during training and +## eval. To completely disable capacity limit, set MOE_DROP_TOKEN to false. +## Larger capacity factor or disabling capacity limit could improve training +## convergence, but will also reduce training throughput. +MOE_TRAIN_CAP_FACTOR=1.0 +MOE_EVAL_CAP_FACTOR=1.0 +MOE_MIN_CAP=4 +MOE_DROP_TOKEN="true" +# MOE_DROP_TOKEN="false" +############################################################################### +### Curriculum learning (CL) configs +## Enable/disable CL +CL_ENABLED="false" +## Consult the tutorial https://www.deepspeed.ai/tutorials/curriculum-learning/ +## for tuning the following configs +CL_START_SEQLEN=80 +CL_AVG_SEQLEN=$(( (${CL_START_SEQLEN} + ${SEQ_LEN}) / 2 )) +CL_TOKENS=60 +CL_TOKENS=$((${CL_TOKENS} * 1000000000)) +CL_STEP=$(( ${CL_TOKENS} / (${GLOBAL_BATCH_SIZE} * ${CL_AVG_SEQLEN}) )) +############################################################################### +### Misc configs +LOG_INTERVAL=10 +EVAL_ITERS=10 +EVAL_INTERVAL=100 +SAVE_INTERVAL=10000 + +## Standard deviation for weight initialization +## We used 0.014 for 350M/1.3B dense/MoE models, and used 0.01 for 6.7B +## dense model. Usually larger model needs lower std. +INIT_STD=0.014 +# INIT_STD=0.01 + +## Activation checkpointing saves GPU memory, but reduces training speed +ACTIVATION_CHECKPOINT="true" +# ACTIVATION_CHECKPOINT="false" +############################################################################### +### Output and data configs +current_time=$(date "+%Y.%m.%d-%H.%M.%S") +host="${HOSTNAME}" +NAME="gpt-${MODEL_SIZE}B-lr-${LR}-minlr-${MIN_LR}-bs-${GLOBAL_BATCH_SIZE}-gpus-${NUM_GPUS}-mp-${MP_SIZE}-pp-${PP_SIZE}" +NAME="${NAME}-ep-pyramid-64+128-mos-mlc-${MLC}-cap-${MOE_TRAIN_CAP_FACTOR}-drop-${MOE_DROP_TOKEN}" + +if [ "${CL_ENABLED}" = "true" ]; then + NAME="${NAME}-cl-${CL_START_SEQLEN}-${CL_STEP}" +fi + +OUTPUT_BASEPATH=$DIR/output +mkdir -p "${OUTPUT_BASEPATH}/tensorboard/" +mkdir -p "${OUTPUT_BASEPATH}/checkpoint/" +mkdir -p "${OUTPUT_BASEPATH}/log/" +TENSORBOARD_DIR="${OUTPUT_BASEPATH}/tensorboard/${NAME}_${host}" +mkdir -p ${TENSORBOARD_DIR} +## Note that for MoE model with billion-scale base model, the checkpoint can be +## as large as TB-scale which normal NFS cannot handle efficiently. +CHECKPOINT_PATH="${OUTPUT_BASEPATH}/checkpoint/${NAME}" + +### Mixture-of-Students (MoS) configs +KD_BETA_CE=1 +CHECKPOINT_PATH_STUDENT="${OUTPUT_BASEPATH}/checkpoint/${NAME}" +CHECKPOINT_PATH_TEACHER="${OUTPUT_BASEPATH}/checkpoint/gpt-1.3B-lr-1.2e-4-minlr-1.0e-6-bs-512-gpus-128-mp-1-pp-1-ep-pyramid-64+128-mlc-0.01-cap-1.0-drop-true/" +CHECKPOINT_PATH_SAVE="${OUTPUT_BASEPATH}/checkpoint/${NAME}" + +USE_INTERNAL_DATA="true" +# USE_INTERNAL_DATA="false" + +if [ "${USE_INTERNAL_DATA}" = "true" ]; then + ## The internal data is only accessible within Microsoft + ## For cluster Azure-EastUS-V100-32GB-4, Azure-WestUS3-A100 + BASE_DATA_PATH=/vc_data/Megatron-LM/data + DATA_HOME="/vc_data/pile-cc1-cc2-shuf" + ## For cluster Lab-RR1-V100 + # BASE_DATA_PATH=/data/Megatron-LM/data + # DATA_HOME="/turing-ssd/users/conglli/data/pile-cc1-cc2-shuf" + ## For cluster Azure-CentralUS-A100 + # BASE_DATA_PATH=/data/Megatron-LM/data + # DATA_HOME=/vc_data_1/users/amawa/blended + + VOCAB_PATH=${BASE_DATA_PATH}/gpt2-vocab.json + MERGE_PATH=${BASE_DATA_PATH}/gpt2-merges.txt + ARX="${DATA_HOME}/ArXiv_ftfy_cleaned_id_shuf_text_document" + BC2="${DATA_HOME}/BookCorpus2_ftfy_cleaned_id_shuf_text_document" + B3="${DATA_HOME}/Books3_ftfy_cleaned_id_shuf_text_document" + CC2020="${DATA_HOME}/CC-2020-50_id_cleaned_shuf_text_document" + CC2021="${DATA_HOME}/CC-2021-04_id_cleaned_shuf_text_document" + GIT="${DATA_HOME}/Github_ftfy_id_shuf_text_document" + GUT="${DATA_HOME}/Gutenberg_PG-19_ftfy_cleaned_id_cleaned_shuf_text_document" + NIH="${DATA_HOME}/NIH_ExPorter_ftfy_id_shuf_text_document" + OWT2="${DATA_HOME}/OpenWebText2_ftfy_cleaned_id_shuf_text_document" + PCC="${DATA_HOME}/Pile-CC_id_cleaned_shuf_text_document" + PM="${DATA_HOME}/PubMed_Abstracts_ftfy_id_shuf_text_document" + RN="${DATA_HOME}/rn_dedup_shuf_cleaned_0.7_cleaned_shuf_text_document" + SE="${DATA_HOME}/StackExchange_ftfy_id_shuf_text_document" + ST="${DATA_HOME}/stories_dedup0.7_shuf_cleaned_shuf_text_document" + WIK="${DATA_HOME}/Wikipedia_en_ftfy_id_shuf_text_document" + DATA_BLEND="0.14336 ${B3} 0.08962 ${RN} 0.19336 ${OWT2} 0.05689 ${SE} \ + 0.00859 ${ST} 0.02897 ${PM} 0.04771 ${WIK} 0.00873 ${GUT} 0.01007 ${BC2} \ + 0.00208 ${NIH} 0.13017 ${CC2020} 0.09446 ${PCC} 0.15652 ${CC2021} \ + 0.01359 ${ARX} 0.01588 ${GIT}" +else + ## Placeholder, we plan to test a public dataset + VOCAB_PATH="" + MERGE_PATH="" + DATA_BLEND="" +fi +############################################################################### +data_options=" \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --data-path ${DATA_BLEND} \ + --data-impl mmap" + +megatron_options=" \ + --override-lr-scheduler \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --tensor-model-parallel-size ${MP_SIZE} \ + --moe-expert-parallel-size ${EP_PARALLEL_SIZE} \ + --num-experts ${EP_SIZE} \ + --moe-loss-coeff ${MLC} \ + --mlp-type residual \ + --moe-train-capacity-factor ${MOE_TRAIN_CAP_FACTOR} \ + --moe-eval-capacity-factor ${MOE_EVAL_CAP_FACTOR} \ + --moe-min-capacity ${MOE_MIN_CAP} \ + --init-method-std ${INIT_STD} \ + --lr-decay-tokens ${LR_DECAY_TOKENS} \ + --lr-warmup-tokens ${WARMUP_TOKENS} \ + --micro-batch-size ${BATCH_SIZE} \ + --exit-duration-in-mins ${EXIT_DURATION} \ + --global-batch-size ${GLOBAL_BATCH_SIZE} \ + --num-layers 21 \ + --hidden-size ${HIDDEN_SIZE} \ + --num-attention-heads ${NUM_ATTN_HEADS} \ + --seq-length ${SEQ_LEN} \ + --max-position-embeddings ${SEQ_LEN} \ + --train-tokens ${TRAIN_TOKENS} \ + --train-iters ${TRAIN_ITERS} \ + --lr ${LR} \ + --min-lr ${MIN_LR} \ + --lr-decay-style cosine \ + --split 98,2,0 \ + --log-interval ${LOG_INTERVAL} \ + --eval-interval ${EVAL_INTERVAL} \ + --eval-iters ${EVAL_ITERS} \ + --save-interval ${SAVE_INTERVAL} \ + --weight-decay 0.1 \ + --clip-grad 1.0 \ + --hysteresis 2 \ + --num-workers 0 \ + --fp16 \ + --load ${CHECKPOINT_PATH_STUDENT} \ + --save ${CHECKPOINT_PATH_SAVE} \ + --mos \ + --kd-beta-ce ${KD_BETA_CE} \ + --num-layers-teacher ${NUM_LAYERS} \ + --num-experts-teacher ${EP_SIZE_TEACHER} \ + --hidden-size-teacher ${HIDDEN_SIZE} \ + --num-attention-heads-teacher ${NUM_ATTN_HEADS} \ + --load-teacher ${CHECKPOINT_PATH_TEACHER} \ + --tensorboard-queue-size 1 \ + --log-timers-to-tensorboard \ + --log-batch-size-to-tensorboard \ + --log-validation-ppl-to-tensorboard \ + --tensorboard-dir ${TENSORBOARD_DIR}" + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +megatron_options="${megatron_options} \ + --checkpoint-activations" +fi + +megatron_options="${megatron_options} \ + --create-moe-param-group" + + +if [ "${MOE_DROP_TOKEN}" = "false" ]; then +megatron_options="${megatron_options} \ + --disable-moe-token-dropping" +fi + +template_json="ds_config_gpt_Zero2_TEMPLATE.json" +config_json="ds_config_gpt_${NAME}.json" +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} + +deepspeed_options=" \ + --deepspeed \ + --deepspeed_config ${config_json} \ + --pipeline-model-parallel-size ${PP_SIZE}" + +# Currently MoE is not compatible with pipeline parallel +deepspeed_options="${deepspeed_options} \ + --no-pipeline-parallel" + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +deepspeed_options="${deepspeed_options} \ + --deepspeed-activation-checkpointing" +fi + +# run_cmd="deepspeed ${DIR}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &> ${OUTPUT_BASEPATH}/log/${NAME}_${host}_${current_time}.log" +run_cmd="deepspeed ${DIR}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &> ${OUTPUT_BASEPATH}/log/${NAME}_${host}.log" +echo ${run_cmd} +eval ${run_cmd} +set +x diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_1.3B_dense.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_1.3B_dense.sh new file mode 100644 index 0000000000000000000000000000000000000000..58bec4f89460d6181ca1b06c087bcc93d24066a3 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_1.3B_dense.sh @@ -0,0 +1,350 @@ +#!/bin/bash +DIR=`pwd` +############################################################################### +### Main configs +## GPT-3 models use 2K sequence length/context window +SEQ_LEN=2048 + +### The "GPT-3 XXX" below are configs from GPT-3 paper +### https://arxiv.org/abs/2005.14165, choose based on +### your desired model size or build your own configs + +## GPT-3 Small 125M +# MODEL_SIZE=0.125 +# NUM_LAYERS=12 +# HIDDEN_SIZE=768 +# NUM_ATTN_HEADS=12 +# GLOBAL_BATCH_SIZE=256 +# LR=6.0e-4 +# MIN_LR=6.0e-5 + +## GPT-3 Medium 350M +# MODEL_SIZE=0.35 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1024 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=3.0e-4 +# MIN_LR=3.0e-5 + +## GPT-3 Large 760M +# MODEL_SIZE=0.76 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1536 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=2.5e-4 +# MIN_LR=2.5e-5 + +## GPT-3 XL 1.3B +MODEL_SIZE=1.3 +NUM_LAYERS=24 +HIDDEN_SIZE=2048 +NUM_ATTN_HEADS=16 +GLOBAL_BATCH_SIZE=512 +LR=2.0e-4 +MIN_LR=2.0e-5 + +## GPT-3 2.7B +# MODEL_SIZE=2.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=2560 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=512 +# LR=1.6e-4 +# MIN_LR=1.6e-5 + +## GPT-3 6.7B +# MODEL_SIZE=6.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=4096 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.2e-4 +# MIN_LR=1.2e-5 + +## GPT-3 13B +# MODEL_SIZE=13 +# NUM_LAYERS=40 +# HIDDEN_SIZE=5120 +# NUM_ATTN_HEADS=40 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.0e-4 +# MIN_LR=1.0e-5 + +## GPT-3 175B +# MODEL_SIZE=175 +# NUM_LAYERS=96 +# HIDDEN_SIZE=12288 +# NUM_ATTN_HEADS=96 +# GLOBAL_BATCH_SIZE=1536 +# LR=0.6e-4 +# MIN_LR=0.6e-5 +############################################################################### +### Training duration configs +## The main termination condition, original GPT-3 paper trains for 300B tokens +## For MoE model, we found sometimes training a bit more to 330B tokens helps +TRAIN_TOKENS=300000000000 +# TRAIN_TOKENS=330000000000 + +## TRAIN_SAMPLES is another termination condition and also affect the number of +## data samples to be indexed. Since we want to reach the TRAIN_TOKENS +## above, and techniques like curriculum learning has less token in some steps, +## so we just set this config large enough to make sure we have enough +## processed data and don't terminate by TRAIN_SAMPLES. +TRAIN_SAMPLES=$(( ${TRAIN_TOKENS} * 3 / ${SEQ_LEN} )) + +## Another termination condition in minutes. Set it large enough to avoid +## undesired early termination. +EXIT_DURATION=30000000 +############################################################################### +### LR configs +## LR warmup and decay duration, this token-based config is preferable since +## no need to readjust when the batch size/seqlen is changed. +## Original GPT-3 paper uses 375M warmup tokens and 260B decay tokens. +## For MoE model, we found that setting the decay token to 300B helps. +WARMUP_TOKENS=375000000 +LR_DECAY_TOKENS=260000000000 +# LR_DECAY_TOKENS=300000000000 +############################################################################### +### Parallelism configs +## Micro batch size per GPU +## Make sure that BATCH_SIZE <= GLOBAL_BATCH_SIZE*PP_SIZE*MP_SIZE/NUM_GPUS +BATCH_SIZE=2 + +## Model parallelism, 1 is no MP +## Currently MoE models have divergence issue when MP > 1. +MP_SIZE=4 + +## Pipeline parallelism +## Currently we don't support PP for MoE. To disable PP, set PP_SIZE +## to 1 and use the "--no-pipeline-parallel" arg. +PP_SIZE=1 +NUM_GPUS=64 +############################################################################### +### MoE configs +## Number of experts. EP_SIZE 1 means dense model without MoE +EP_SIZE=1 +# EP_SIZE=128 + +if [[ $EP_SIZE -gt $NUM_GPUS ]]; then + EP_PARALLEL_SIZE=$NUM_GPUS +else + EP_PARALLEL_SIZE=$EP_SIZE +fi + +## Original GPT-3 model always set min LR at 10% of max LR. For MoE model, we +## found that lower LR and min LR (than the base dense model) helps. +## For 1.3B MoE-128 model we used LR=1.2e-4 and MIN_LR=1.0e-6. +## For 350M MoE-128 model we used LR=2.0e-4 and MIN_LR=2.0e-6, but they are not +## heavily tuned. +# LR=2.0e-4 +# MIN_LR=2e-06 + +## Coefficient for MoE loss. We find that 0.01 is a good value at least for +## 1.3B MoE-128 model +MLC=0.01 + +## Below configs adjust the MoE expert token capacity limit during training and +## eval. To completely disable capacity limit, set MOE_DROP_TOKEN to false. +## Larger capacity factor or disabling capacity limit could improve training +## convergence, but will also reduce training throughput. +MOE_TRAIN_CAP_FACTOR=1.0 +MOE_EVAL_CAP_FACTOR=1.0 +MOE_MIN_CAP=4 +MOE_DROP_TOKEN="true" +# MOE_DROP_TOKEN="false" +############################################################################### +### Curriculum learning (CL) configs +## Enable/disable CL +CL_ENABLED="false" +## Consult the tutorial https://www.deepspeed.ai/tutorials/curriculum-learning/ +## for tuning the following configs +CL_START_SEQLEN=80 +CL_AVG_SEQLEN=$(( (${CL_START_SEQLEN} + ${SEQ_LEN}) / 2 )) +CL_TOKENS=60 +CL_TOKENS=$((${CL_TOKENS} * 1000000000)) +CL_STEP=$(( ${CL_TOKENS} / (${GLOBAL_BATCH_SIZE} * ${CL_AVG_SEQLEN}) )) +############################################################################### +### Misc configs +LOG_INTERVAL=10 +EVAL_ITERS=10 +EVAL_INTERVAL=100 +SAVE_INTERVAL=1000 + +## Standard deviation for weight initialization +## We used 0.014 for 350M/1.3B dense/MoE models, and used 0.01 for 6.7B +## dense model. Usually larger model needs lower std. +INIT_STD=0.014 +# INIT_STD=0.01 + +## Activation checkpointing saves GPU memory, but reduces training speed +ACTIVATION_CHECKPOINT="true" +# ACTIVATION_CHECKPOINT="false" +############################################################################### +### Output and data configs +current_time=$(date "+%Y.%m.%d-%H.%M.%S") +host="${HOSTNAME}" +NAME="gpt-${MODEL_SIZE}B-lr-${LR}-minlr-${MIN_LR}-bs-${GLOBAL_BATCH_SIZE}-gpus-${NUM_GPUS}-mp-${MP_SIZE}-pp-${PP_SIZE}" +if [[ $EP_SIZE -gt 1 ]]; then + NAME="${NAME}-ep-${EP_SIZE}-mlc-${MLC}-cap-${MOE_TRAIN_CAP_FACTOR}-drop-${MOE_DROP_TOKEN}" +fi +if [ "${CL_ENABLED}" = "true" ]; then + NAME="${NAME}-cl-${CL_START_SEQLEN}-${CL_STEP}" +fi + +OUTPUT_BASEPATH=$DIR/output +mkdir -p "${OUTPUT_BASEPATH}/tensorboard/" +mkdir -p "${OUTPUT_BASEPATH}/checkpoint/" +mkdir -p "${OUTPUT_BASEPATH}/log/" +TENSORBOARD_DIR="${OUTPUT_BASEPATH}/tensorboard/${NAME}_${host}_${current_time}" +mkdir -p ${TENSORBOARD_DIR} +## Note that for MoE model with billion-scale base model, the checkpoint can be +## as large as TB-scale which normal NFS cannot handle efficiently. +CHECKPOINT_PATH="${OUTPUT_BASEPATH}/checkpoint/${NAME}" + +# USE_INTERNAL_DATA="true" +USE_INTERNAL_DATA="false" + +if [ "${USE_INTERNAL_DATA}" = "true" ]; then + ## The internal data is only accessible within Microsoft + ## For cluster Azure-EastUS-V100-32GB-4, Azure-WestUS3-A100 + # BASE_DATA_PATH=/vc_data/Megatron-LM/data + # DATA_HOME="/vc_data/pile-cc1-cc2-shuf" + ## For cluster Lab-RR1-V100 + BASE_DATA_PATH=/data/Megatron-LM/data + DATA_HOME="/turing-ssd/users/conglli/data/pile-cc1-cc2-shuf" + ## For cluster Azure-CentralUS-A100 + # BASE_DATA_PATH=/data/Megatron-LM/data + # DATA_HOME=/vc_data_1/users/amawa/blended + + VOCAB_PATH=${BASE_DATA_PATH}/gpt2-vocab.json + MERGE_PATH=${BASE_DATA_PATH}/gpt2-merges.txt + ARX="${DATA_HOME}/ArXiv_ftfy_cleaned_id_shuf_text_document" + BC2="${DATA_HOME}/BookCorpus2_ftfy_cleaned_id_shuf_text_document" + B3="${DATA_HOME}/Books3_ftfy_cleaned_id_shuf_text_document" + CC2020="${DATA_HOME}/CC-2020-50_id_cleaned_shuf_text_document" + CC2021="${DATA_HOME}/CC-2021-04_id_cleaned_shuf_text_document" + GIT="${DATA_HOME}/Github_ftfy_id_shuf_text_document" + GUT="${DATA_HOME}/Gutenberg_PG-19_ftfy_cleaned_id_cleaned_shuf_text_document" + NIH="${DATA_HOME}/NIH_ExPorter_ftfy_id_shuf_text_document" + OWT2="${DATA_HOME}/OpenWebText2_ftfy_cleaned_id_shuf_text_document" + PCC="${DATA_HOME}/Pile-CC_id_cleaned_shuf_text_document" + PM="${DATA_HOME}/PubMed_Abstracts_ftfy_id_shuf_text_document" + RN="${DATA_HOME}/rn_dedup_shuf_cleaned_0.7_cleaned_shuf_text_document" + SE="${DATA_HOME}/StackExchange_ftfy_id_shuf_text_document" + ST="${DATA_HOME}/stories_dedup0.7_shuf_cleaned_shuf_text_document" + WIK="${DATA_HOME}/Wikipedia_en_ftfy_id_shuf_text_document" + DATA_BLEND="0.14336 ${B3} 0.08962 ${RN} 0.19336 ${OWT2} 0.05689 ${SE} \ + 0.00859 ${ST} 0.02897 ${PM} 0.04771 ${WIK} 0.00873 ${GUT} 0.01007 ${BC2} \ + 0.00208 ${NIH} 0.13017 ${CC2020} 0.09446 ${PCC} 0.15652 ${CC2021} \ + 0.01359 ${ARX} 0.01588 ${GIT}" +else + VOCAB_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-vocab.json + MERGE_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-merges.txt + # Public the Pile dataset, can be downloaded at https://mystic.the-eye.eu/public/AI/pile_neox/ + DATA_BLEND=/data/the_pile_public_merged_nopreprocessing/pile_text_document +fi +############################################################################### +data_options=" \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --data-path ${DATA_BLEND} \ + --data-impl mmap" + +megatron_options=" \ + --override-lr-scheduler \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --tensor-model-parallel-size ${MP_SIZE} \ + --moe-expert-parallel-size ${EP_PARALLEL_SIZE} \ + --num-experts ${EP_SIZE} \ + --moe-loss-coeff ${MLC} \ + --moe-train-capacity-factor ${MOE_TRAIN_CAP_FACTOR} \ + --moe-eval-capacity-factor ${MOE_EVAL_CAP_FACTOR} \ + --moe-min-capacity ${MOE_MIN_CAP} \ + --init-method-std ${INIT_STD} \ + --lr-decay-tokens ${LR_DECAY_TOKENS} \ + --lr-warmup-tokens ${WARMUP_TOKENS} \ + --micro-batch-size ${BATCH_SIZE} \ + --exit-duration-in-mins ${EXIT_DURATION} \ + --rampup-batch-size 32 32 1953125 \ + --global-batch-size ${GLOBAL_BATCH_SIZE} \ + --num-layers ${NUM_LAYERS} \ + --hidden-size ${HIDDEN_SIZE} \ + --num-attention-heads ${NUM_ATTN_HEADS} \ + --seq-length ${SEQ_LEN} \ + --max-position-embeddings ${SEQ_LEN} \ + --train-tokens ${TRAIN_TOKENS} \ + --train-samples ${TRAIN_SAMPLES} \ + --lr ${LR} \ + --min-lr ${MIN_LR} \ + --lr-decay-style cosine \ + --split 98,2,0 \ + --log-interval ${LOG_INTERVAL} \ + --eval-interval ${EVAL_INTERVAL} \ + --eval-iters ${EVAL_ITERS} \ + --save-interval ${SAVE_INTERVAL} \ + --weight-decay 0.1 \ + --clip-grad 1.0 \ + --hysteresis 2 \ + --num-workers 0 \ + --fp16 \ + --load ${CHECKPOINT_PATH} \ + --save ${CHECKPOINT_PATH} \ + --tensorboard-queue-size 1 \ + --log-timers-to-tensorboard \ + --log-batch-size-to-tensorboard \ + --log-validation-ppl-to-tensorboard \ + --tensorboard-dir ${TENSORBOARD_DIR}" + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +megatron_options="${megatron_options} \ + --checkpoint-activations" +fi + +if [[ $EP_SIZE -gt 1 ]]; then +megatron_options="${megatron_options} \ + --create-moe-param-group" +fi + +if [ "${MOE_DROP_TOKEN}" = "false" ]; then +megatron_options="${megatron_options} \ + --disable-moe-token-dropping" +fi + +template_json="ds_config_gpt_TEMPLATE.json" +config_json="ds_config_gpt_${NAME}.json" +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/ZERO_STAGE/0/" \ + | sed "s/PRESCALE_GRAD/true/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} + +deepspeed_options=" \ + --deepspeed \ + --deepspeed_config ${config_json} \ + --pipeline-model-parallel-size ${PP_SIZE}" + +# Currently MoE is not compatible with pipeline parallel +if [[ $EP_SIZE -gt 1 ]]; then +deepspeed_options="${deepspeed_options} \ + --no-pipeline-parallel" +fi + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +deepspeed_options="${deepspeed_options} \ + --deepspeed-activation-checkpointing" +fi + +run_cmd="deepspeed ${DIR}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &> ${OUTPUT_BASEPATH}/log/${NAME}_${host}_${current_time}.log" +echo ${run_cmd} +eval ${run_cmd} +set +x diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_1.3B_dense_cl.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_1.3B_dense_cl.sh new file mode 100644 index 0000000000000000000000000000000000000000..6f76e9e113203cc66b7a663c65fcea31fab78b81 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_1.3B_dense_cl.sh @@ -0,0 +1,285 @@ +#!/bin/bash +DIR=`pwd` +############################################################################### +### Main configs +## GPT-3 models use 2K sequence length/context window +SEQ_LEN=2048 + +### The "GPT-3 XXX" below are configs from GPT-3 paper +### https://arxiv.org/abs/2005.14165, choose based on +### your desired model size or build your own configs + +## GPT-3 Small 125M +# MODEL_SIZE=0.125 +# NUM_LAYERS=12 +# HIDDEN_SIZE=768 +# NUM_ATTN_HEADS=12 +# GLOBAL_BATCH_SIZE=256 +# LR=6.0e-4 +# MIN_LR=6.0e-5 + +## GPT-3 Medium 350M +# MODEL_SIZE=0.35 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1024 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=3.0e-4 +# MIN_LR=3.0e-5 + +## GPT-3 Large 760M +# MODEL_SIZE=0.76 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1536 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=2.5e-4 +# MIN_LR=2.5e-5 + +## GPT-3 XL 1.3B +MODEL_SIZE=1.3 +NUM_LAYERS=24 +HIDDEN_SIZE=2048 +NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=512 +# LR=2.0e-4 +MIN_LR=2.0e-5 + +# Curriculum learning (CL) enables stable large-batch training +GLOBAL_BATCH_SIZE=4096 # 8x +LR=8.0e-4 # 4x + +## GPT-3 2.7B +# MODEL_SIZE=2.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=2560 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=512 +# LR=1.6e-4 +# MIN_LR=1.6e-5 + +## GPT-3 6.7B +# MODEL_SIZE=6.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=4096 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.2e-4 +# MIN_LR=1.2e-5 + +## GPT-3 13B +# MODEL_SIZE=13 +# NUM_LAYERS=40 +# HIDDEN_SIZE=5120 +# NUM_ATTN_HEADS=40 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.0e-4 +# MIN_LR=1.0e-5 + +## GPT-3 175B +# MODEL_SIZE=175 +# NUM_LAYERS=96 +# HIDDEN_SIZE=12288 +# NUM_ATTN_HEADS=96 +# GLOBAL_BATCH_SIZE=1536 +# LR=0.6e-4 +# MIN_LR=0.6e-5 +############################################################################### +### Training duration configs +## The main termination condition, original GPT-3 paper trains for 300B tokens +TRAIN_TOKENS=300000000000 + +## TRAIN_SAMPLES is another termination condition and also affect the number of +## data samples to be indexed. Since we want to reach the TRAIN_TOKENS +## above, and techniques like curriculum learning has less token in some samples, +## so we just set this config large enough to make sure we have enough +## processed data and don't terminate by TRAIN_SAMPLES. +TRAIN_SAMPLES=$(( ${TRAIN_TOKENS} * 3 / ${SEQ_LEN} )) + +## Another termination condition in minutes. Set it large enough to avoid +## undesired early termination. +EXIT_DURATION=30000000 +############################################################################### +### LR configs +## LR warmup and decay duration, this token-based config is preferable since +## no need to readjust when the batch size/seqlen is changed. +## Original GPT-3 paper uses 375M warmup tokens and 260B decay tokens. +WARMUP_TOKENS=375000000 +LR_DECAY_TOKENS=260000000000 +############################################################################### +### Parallelism configs +## Micro batch size per GPU +## Make sure that BATCH_SIZE <= GLOBAL_BATCH_SIZE*PP_SIZE*MP_SIZE/NUM_GPUS +BATCH_SIZE=16 + +## Model parallelism, 1 is no MP +MP_SIZE=2 + +## Pipeline parallelism. To disable PP, set PP_SIZE to 1 and NO_PP to true. +PP_SIZE=1 +NO_PP="true" + +## ZeRO stage +ZERO_STAGE=0 + +## Total number of GPUs +NUM_GPUS=128 +DP_SIZE=$(( ${NUM_GPUS} / ${PP_SIZE} / ${MP_SIZE} )) +############################################################################### +### Curriculum learning (CL) configs +## Enable/disable CL +CL_ENABLED="true" +## Consult the tutorial https://www.deepspeed.ai/tutorials/curriculum-learning/ +## for tuning the following configs +CL_START_SEQLEN=80 +CL_AVG_SEQLEN=$(( (${CL_START_SEQLEN} + ${SEQ_LEN}) / 2 )) +CL_TOKENS=60 +CL_STEP=$(( ${CL_TOKENS} * 1000000000 / (${GLOBAL_BATCH_SIZE} * ${CL_AVG_SEQLEN}) )) +############################################################################### +### Misc configs +LOG_INTERVAL=10 +EVAL_ITERS=10 +EVAL_INTERVAL=100 +SAVE_INTERVAL=1000 + +## Standard deviation for weight initialization. Usually larger model needs +## lower std. We used a heuristic equation of sqrt(1/3/HIDDEN_SIZE) from the +## MT-NLG 530B work (https://arxiv.org/pdf/2201.11990.pdf) +INIT_STD=0.013 + +## Activation checkpointing saves GPU memory, but reduces training speed +ACTIVATION_CHECKPOINT="true" +# ACTIVATION_CHECKPOINT="false" + +## Whether or not log optimizer states (norms, max abs values) to tensorboard. +## This is not required for training and might save GPU memory when turned off. +LOG_OPTIMIZER_STATE="true" +############################################################################### +### Output and data configs +current_time=$(date "+%Y.%m.%d-%H.%M.%S") +host="${HOSTNAME}" +NAME="gpt3-with-pile-${MODEL_SIZE}B-lr-${LR}-minlr-${MIN_LR}-bs-${GLOBAL_BATCH_SIZE}-gpus-${NUM_GPUS}-zero-${ZERO_STAGE}-mp-${MP_SIZE}-pp-${PP_SIZE}" +if [ "${NO_PP}" = "true" ]; then + NAME="${NAME}-no_pp" +fi +if [ "${CL_ENABLED}" = "true" ]; then + NAME="${NAME}-cl-startseqlen-${CL_START_SEQLEN}-step-${CL_STEP}-token-${CL_TOKENS}B" +fi + +LOG_PATH="log/" +TENSORBOARD_PATH="tensorboard/${NAME}_${host}_${current_time}" +CHECKPOINT_PATH="/blob/users/conglli/project/gpt3_with_pile/checkpoint/${NAME}" +mkdir -p ${LOG_PATH} +mkdir -p ${TENSORBOARD_PATH} +mkdir -p ${CHECKPOINT_PATH} + +VOCAB_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-vocab.json +MERGE_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-merges.txt +# Public the Pile dataset, can be downloaded at https://mystic.the-eye.eu/public/AI/pile_neox/ +DATA_PATH=/data/the_pile_public_merged_nopreprocessing/pile_text_document +############################################################################### +data_options=" \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --data-path ${DATA_PATH} \ + --data-impl mmap" + +megatron_options=" \ + --override-lr-scheduler \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --tensor-model-parallel-size ${MP_SIZE} \ + --init-method-std ${INIT_STD} \ + --lr-decay-tokens ${LR_DECAY_TOKENS} \ + --lr-warmup-tokens ${WARMUP_TOKENS} \ + --micro-batch-size ${BATCH_SIZE} \ + --exit-duration-in-mins ${EXIT_DURATION} \ + --global-batch-size ${GLOBAL_BATCH_SIZE} \ + --num-layers ${NUM_LAYERS} \ + --hidden-size ${HIDDEN_SIZE} \ + --num-attention-heads ${NUM_ATTN_HEADS} \ + --seq-length ${SEQ_LEN} \ + --max-position-embeddings ${SEQ_LEN} \ + --train-tokens ${TRAIN_TOKENS} \ + --train-samples ${TRAIN_SAMPLES} \ + --lr ${LR} \ + --min-lr ${MIN_LR} \ + --lr-decay-style cosine \ + --split 98,2,0 \ + --log-interval ${LOG_INTERVAL} \ + --eval-interval ${EVAL_INTERVAL} \ + --eval-iters ${EVAL_ITERS} \ + --save-interval ${SAVE_INTERVAL} \ + --weight-decay 0.1 \ + --clip-grad 1.0 \ + --hysteresis 2 \ + --num-workers 0 \ + --fp16 \ + --load ${CHECKPOINT_PATH} \ + --save ${CHECKPOINT_PATH} \ + --tensorboard-queue-size 1 \ + --log-timers-to-tensorboard \ + --log-batch-size-to-tensorboard \ + --log-validation-ppl-to-tensorboard \ + --tensorboard-dir ${TENSORBOARD_PATH}" + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +megatron_options="${megatron_options} \ + --checkpoint-activations" +fi + +if [ "${LOG_OPTIMIZER_STATE}" = "true" ]; then +megatron_options="${megatron_options} \ + --log-optimizer-states-to-tensorboard" +fi + +template_json="ds_config_gpt_TEMPLATE.json" +config_json="ds_config_${NAME}.json" +if [[ $ZERO_STAGE -gt 0 ]]; then +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/ZERO_STAGE/${ZERO_STAGE}/" \ + | sed "s/PRESCALE_GRAD/false/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} +else +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/ZERO_STAGE/${ZERO_STAGE}/" \ + | sed "s/PRESCALE_GRAD/true/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} +fi + +deepspeed_options=" \ + --deepspeed \ + --deepspeed_config ${config_json} \ + --zero-stage ${ZERO_STAGE} \ + --pipeline-model-parallel-size ${PP_SIZE}" + +if [[ "${NO_PP}" = "true" ]]; then +deepspeed_options="${deepspeed_options} \ + --no-pipeline-parallel" +fi + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +deepspeed_options="${deepspeed_options} \ + --deepspeed-activation-checkpointing" +fi + +run_cmd="deepspeed ${DIR}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &> ${LOG_PATH}/${NAME}_${host}_${current_time}.log" +echo ${run_cmd} +eval ${run_cmd} +set +x diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_125M_MoE64.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_125M_MoE64.sh new file mode 100644 index 0000000000000000000000000000000000000000..d4fe35b7bad8408687bec9882582d85640562457 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_125M_MoE64.sh @@ -0,0 +1,373 @@ +#!/bin/bash +DIR=`pwd` +############################################################################### +### Main configs +## GPT-3 models use 2K sequence length/context window +SEQ_LEN=2048 + +### The "GPT-3 XXX" below are configs from GPT-3 paper +### https://arxiv.org/abs/2005.14165, choose based on +### your desired model size or build your own configs + +## GPT-3 Small 125M +MODEL_SIZE=0.125 +NUM_LAYERS=12 +HIDDEN_SIZE=768 +NUM_ATTN_HEADS=12 +GLOBAL_BATCH_SIZE=256 +# LR=6.0e-4 +# MIN_LR=6.0e-5 + +## GPT-3 Medium 350M +# MODEL_SIZE=0.35 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1024 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=3.0e-4 +# MIN_LR=3.0e-5 + +## GPT-3 Large 760M +# MODEL_SIZE=0.76 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1536 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=2.5e-4 +# MIN_LR=2.5e-5 + +## GPT-3 XL 1.3B +# MODEL_SIZE=1.3 +# NUM_LAYERS=24 +# HIDDEN_SIZE=2048 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=512 +# LR=2.0e-4 +# MIN_LR=2.0e-5 + +## GPT-3 2.7B +# MODEL_SIZE=2.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=2560 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=512 +# LR=1.6e-4 +# MIN_LR=1.6e-5 + +## GPT-3 6.7B +# MODEL_SIZE=6.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=4096 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.2e-4 +# MIN_LR=1.2e-5 + +## GPT-3 13B +# MODEL_SIZE=13 +# NUM_LAYERS=40 +# HIDDEN_SIZE=5120 +# NUM_ATTN_HEADS=40 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.0e-4 +# MIN_LR=1.0e-5 + +## GPT-3 175B +# MODEL_SIZE=175 +# NUM_LAYERS=96 +# HIDDEN_SIZE=12288 +# NUM_ATTN_HEADS=96 +# GLOBAL_BATCH_SIZE=1536 +# LR=0.6e-4 +# MIN_LR=0.6e-5 +############################################################################### +### Training duration configs +## The main termination condition, original GPT-3 paper trains for 300B tokens +## For MoE model, we found sometimes training a bit more to 330B tokens helps +TRAIN_TOKENS=300000000000 +# TRAIN_TOKENS=330000000000 + +## TRAIN_ITERS is another termination condition and also affect the number of +## data samples to be indexed. Since we want to reach the TRAIN_TOKENS +## above, and techniques like curriculum learning has less token in some steps, +## so we just set this config large enough to make sure we have enough +## processed data and don't terminate by TRAIN_ITERS. +TRAIN_ITERS=$(( ${TRAIN_TOKENS} * 3 / ${GLOBAL_BATCH_SIZE} / ${SEQ_LEN} )) + +## Another termination condition in minutes. Set it large enough to avoid +## undesired early termination. +EXIT_DURATION=30000000 +############################################################################### +### LR configs +## LR warmup and decay duration, this token-based config is preferable since +## no need to readjust when the batch size/seqlen is changed. +## Original GPT-3 paper uses 375M warmup tokens and 260B decay tokens. +## For MoE model, we found that setting the decay token to 300B helps. +WARMUP_TOKENS=375000000 +# LR_DECAY_TOKENS=260000000000 +LR_DECAY_TOKENS=300000000000 +############################################################################### +### Parallelism configs +## Micro batch size per GPU +## Make sure that BATCH_SIZE <= GLOBAL_BATCH_SIZE*PP_SIZE*MP_SIZE/NUM_GPUS +BATCH_SIZE=4 + +## Model parallelism, 1 is no MP +## Currently MoE models have divergence issue when MP > 1. +MP_SIZE=1 + +## Pipeline parallelism +## Currently we don't support PP for MoE. To disable PP, set PP_SIZE +## to 1 and use the "--no-pipeline-parallel" arg. +PP_SIZE=1 +NUM_GPUS=$(($(ds_ssh nvidia-smi --query-gpu=name --format=csv,noheader | wc -l)-2)) +NUM_GPUS_PERNODE=$(nvidia-smi --query-gpu=name --format=csv,noheader | wc -l) +NUM_NODE=$(( ${NUM_GPUS} / ${NUM_GPUS_PERNODE} )) +############################################################################### +### MoE configs +## Number of experts. EP_SIZE 1 means dense model without MoE +# EP_SIZE=1 +EP_SIZE=64 + +if [[ $EP_SIZE -gt $NUM_GPUS ]]; then + EP_PARALLEL_SIZE=$NUM_GPUS +else + EP_PARALLEL_SIZE=$EP_SIZE +fi + +## Original GPT-3 model always set min LR at 10% of max LR. For MoE model, we +## found that lower LR and min LR (than the base dense model) helps. +## For 1.3B MoE-128 model we used LR=1.2e-4 and MIN_LR=1.0e-6. +## For 350M MoE-128 model we used LR=2.0e-4 and MIN_LR=2.0e-6, but they are not +## heavily tuned. +LR=4.5e-4 +MIN_LR=4.5e-06 + +## Coefficient for MoE loss. We find that 0.01 is a good value at least for +## 1.3B MoE-128 model +MLC=0.01 + +## Below configs adjust the MoE expert token capacity limit during training and +## eval. To completely disable capacity limit, set MOE_DROP_TOKEN to false. +## Larger capacity factor or disabling capacity limit could improve training +## convergence, but will also reduce training throughput. +MOE_TRAIN_CAP_FACTOR=1.0 +MOE_EVAL_CAP_FACTOR=1.0 +MOE_MIN_CAP=4 +MOE_DROP_TOKEN="true" +# MOE_DROP_TOKEN="false" +############################################################################### +### Curriculum learning (CL) configs +## Enable/disable CL +CL_ENABLED="false" +## Consult the tutorial https://www.deepspeed.ai/tutorials/curriculum-learning/ +## for tuning the following configs +CL_START_SEQLEN=80 +CL_AVG_SEQLEN=$(( (${CL_START_SEQLEN} + ${SEQ_LEN}) / 2 )) +CL_TOKENS=60 +CL_TOKENS=$((${CL_TOKENS} * 1000000000)) +CL_STEP=$(( ${CL_TOKENS} / (${GLOBAL_BATCH_SIZE} * ${CL_AVG_SEQLEN}) )) +############################################################################### +### Misc configs +LOG_INTERVAL=10 +EVAL_ITERS=10 +EVAL_INTERVAL=100 +SAVE_INTERVAL=10000 + +## Standard deviation for weight initialization +## We used 0.014 for 350M/1.3B dense/MoE models, and used 0.01 for 6.7B +## dense model. Usually larger model needs lower std. +INIT_STD=0.014 +# INIT_STD=0.01 + +## Activation checkpointing saves GPU memory, but reduces training speed +ACTIVATION_CHECKPOINT="true" +# ACTIVATION_CHECKPOINT="false" +############################################################################### +### Output and data configs +current_time=$(date "+%Y.%m.%d-%H.%M.%S") +host="${HOSTNAME}" +NAME="gpt-${MODEL_SIZE}B-lr-${LR}-minlr-${MIN_LR}-bs-${GLOBAL_BATCH_SIZE}-gpus-${NUM_GPUS}-mp-${MP_SIZE}-pp-${PP_SIZE}" +if [[ $EP_SIZE -gt 1 ]]; then + NAME="${NAME}-ep-${EP_SIZE}-mlc-${MLC}-cap-${MOE_TRAIN_CAP_FACTOR}-drop-${MOE_DROP_TOKEN}" +fi +if [ "${CL_ENABLED}" = "true" ]; then + NAME="${NAME}-cl-${CL_START_SEQLEN}-${CL_STEP}" +fi + +OUTPUT_BASEPATH=$DIR/output +mkdir -p "${OUTPUT_BASEPATH}/tensorboard/" +mkdir -p "${OUTPUT_BASEPATH}/checkpoint/" +mkdir -p "${OUTPUT_BASEPATH}/log/" +TENSORBOARD_DIR="${OUTPUT_BASEPATH}/tensorboard/${NAME}_${host}_${current_time}" +mkdir -p ${TENSORBOARD_DIR} +## Note that for MoE model with billion-scale base model, the checkpoint can be +## as large as TB-scale which normal NFS cannot handle efficiently. +CHECKPOINT_PATH="${OUTPUT_BASEPATH}/checkpoint/${NAME}" + +# USE_INTERNAL_DATA="true" +USE_INTERNAL_DATA="false" + +if [ "${USE_INTERNAL_DATA}" = "true" ]; then + ## The internal data is only accessible within Microsoft + ## For cluster Azure-EastUS-V100-32GB-4, Azure-WestUS3-A100 + # BASE_DATA_PATH=/vc_data/Megatron-LM/data + # DATA_HOME="/vc_data/pile-cc1-cc2-shuf" + ## For cluster Lab-RR1-V100 + BASE_DATA_PATH=/data/Megatron-LM/data + DATA_HOME="/turing-ssd/users/conglli/data/pile-cc1-cc2-shuf" + ## For cluster Azure-CentralUS-A100 + # BASE_DATA_PATH=/data/Megatron-LM/data + # DATA_HOME=/vc_data_1/users/amawa/blended + + VOCAB_PATH=${BASE_DATA_PATH}/gpt2-vocab.json + MERGE_PATH=${BASE_DATA_PATH}/gpt2-merges.txt + ARX="${DATA_HOME}/ArXiv_ftfy_cleaned_id_shuf_text_document" + BC2="${DATA_HOME}/BookCorpus2_ftfy_cleaned_id_shuf_text_document" + B3="${DATA_HOME}/Books3_ftfy_cleaned_id_shuf_text_document" + CC2020="${DATA_HOME}/CC-2020-50_id_cleaned_shuf_text_document" + CC2021="${DATA_HOME}/CC-2021-04_id_cleaned_shuf_text_document" + GIT="${DATA_HOME}/Github_ftfy_id_shuf_text_document" + GUT="${DATA_HOME}/Gutenberg_PG-19_ftfy_cleaned_id_cleaned_shuf_text_document" + NIH="${DATA_HOME}/NIH_ExPorter_ftfy_id_shuf_text_document" + OWT2="${DATA_HOME}/OpenWebText2_ftfy_cleaned_id_shuf_text_document" + PCC="${DATA_HOME}/Pile-CC_id_cleaned_shuf_text_document" + PM="${DATA_HOME}/PubMed_Abstracts_ftfy_id_shuf_text_document" + RN="${DATA_HOME}/rn_dedup_shuf_cleaned_0.7_cleaned_shuf_text_document" + SE="${DATA_HOME}/StackExchange_ftfy_id_shuf_text_document" + ST="${DATA_HOME}/stories_dedup0.7_shuf_cleaned_shuf_text_document" + WIK="${DATA_HOME}/Wikipedia_en_ftfy_id_shuf_text_document" + DATA_PATH="0.14336 ${B3} 0.08962 ${RN} 0.19336 ${OWT2} 0.05689 ${SE} \ + 0.00859 ${ST} 0.02897 ${PM} 0.04771 ${WIK} 0.00873 ${GUT} 0.01007 ${BC2} \ + 0.00208 ${NIH} 0.13017 ${CC2020} 0.09446 ${PCC} 0.15652 ${CC2021} \ + 0.01359 ${ARX} 0.01588 ${GIT}" +else + VOCAB_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-vocab.json + MERGE_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-merges.txt + # Public the Pile dataset, can be downloaded at https://mystic.the-eye.eu/public/AI/pile_neox/ + # For cluster Azure-EastUS-V100-32GB-4, Lab-RR1-V100 + DATA_PATH=/vc_data_blob/users/conglli/the_pile_public_merged_nopreprocessing/pile_text_document + # For cluster Azure-WestUS3-A100 + # DATA_PATH=/blob/data/the_pile_public_merged_nopreprocessing/pile_text_document +fi +############################################################################### +data_options=" \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --data-path ${DATA_PATH} \ + --data-impl mmap" + +megatron_options=" \ + --override-lr-scheduler \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --tensor-model-parallel-size ${MP_SIZE} \ + --moe-expert-parallel-size ${EP_PARALLEL_SIZE} \ + --num-experts ${EP_SIZE} \ + --moe-loss-coeff ${MLC} \ + --moe-train-capacity-factor ${MOE_TRAIN_CAP_FACTOR} \ + --moe-eval-capacity-factor ${MOE_EVAL_CAP_FACTOR} \ + --moe-min-capacity ${MOE_MIN_CAP} \ + --init-method-std ${INIT_STD} \ + --lr-decay-tokens ${LR_DECAY_TOKENS} \ + --lr-warmup-tokens ${WARMUP_TOKENS} \ + --micro-batch-size ${BATCH_SIZE} \ + --exit-duration-in-mins ${EXIT_DURATION} \ + --global-batch-size ${GLOBAL_BATCH_SIZE} \ + --num-layers ${NUM_LAYERS} \ + --hidden-size ${HIDDEN_SIZE} \ + --num-attention-heads ${NUM_ATTN_HEADS} \ + --seq-length ${SEQ_LEN} \ + --max-position-embeddings ${SEQ_LEN} \ + --train-tokens ${TRAIN_TOKENS} \ + --train-iters ${TRAIN_ITERS} \ + --lr ${LR} \ + --min-lr ${MIN_LR} \ + --lr-decay-style cosine \ + --split 98,2,0 \ + --log-interval ${LOG_INTERVAL} \ + --eval-interval ${EVAL_INTERVAL} \ + --eval-iters ${EVAL_ITERS} \ + --save-interval ${SAVE_INTERVAL} \ + --weight-decay 0.1 \ + --clip-grad 1.0 \ + --hysteresis 2 \ + --num-workers 0 \ + --fp16 \ + --load ${CHECKPOINT_PATH} \ + --save ${CHECKPOINT_PATH} \ + --tensorboard-queue-size 1 \ + --log-timers-to-tensorboard \ + --log-batch-size-to-tensorboard \ + --log-validation-ppl-to-tensorboard \ + --tensorboard-dir ${TENSORBOARD_DIR}" + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +megatron_options="${megatron_options} \ + --checkpoint-activations" +fi + +if [[ $EP_SIZE -gt 1 ]]; then +megatron_options="${megatron_options} \ + --create-moe-param-group" +fi + +if [ "${MOE_DROP_TOKEN}" = "false" ]; then +megatron_options="${megatron_options} \ + --disable-moe-token-dropping" +fi + +template_json="ds_config_gpt_TEMPLATE.json" +config_json="ds_config_gpt_${NAME}.json" +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/ZERO_STAGE/0/" \ + | sed "s/PRESCALE_GRAD/true/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} + +deepspeed_options=" \ + --deepspeed \ + --deepspeed_config ${config_json} \ + --pipeline-model-parallel-size ${PP_SIZE}" + +# Currently MoE is not compatible with pipeline parallel +if [[ $EP_SIZE -gt 1 ]]; then +deepspeed_options="${deepspeed_options} \ + --no-pipeline-parallel" +fi + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +deepspeed_options="${deepspeed_options} \ + --deepspeed-activation-checkpointing" +fi + +## When saving checkpoint to a storage with cache, their could be consistency +## issue of the pointer to latest checkpoint. Here we find the correct pointer +## and broadcast it to all nodes. +ITERATION_FILE="$CHECKPOINT_PATH/latest_checkpointed_iteration.txt" +ITERATION_FILE_2="$CHECKPOINT_PATH/latest" +ITERATION=0 +for (( node = 0; node <= NUM_NODE-1; node++ )) +do + if $(ssh -q worker-"$node" "test -f \"$ITERATION_FILE\""); then + LOCAL_ITERATION=$(ssh -q worker-"$node" cat $ITERATION_FILE) + ITERATION=$(( ${LOCAL_ITERATION} > ${ITERATION} ? ${LOCAL_ITERATION} : ${ITERATION} )) + fi +done +if [[ $ITERATION -gt 0 ]]; then + ITERATION_2="global_step${ITERATION}" + ds_ssh "echo $ITERATION > $ITERATION_FILE" + ds_ssh "echo $ITERATION_2 > $ITERATION_FILE_2" +fi + +run_cmd="deepspeed ${DIR}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &> ${OUTPUT_BASEPATH}/log/${NAME}_${host}_${current_time}.log" +echo ${run_cmd} +eval ${run_cmd} +set +x diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_125M_dense_cl.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_125M_dense_cl.sh new file mode 100644 index 0000000000000000000000000000000000000000..110cef4571727096b5485a81bda6587cf550c28e --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_125M_dense_cl.sh @@ -0,0 +1,309 @@ +#!/bin/bash +DIR=`pwd` +############################################################################### +### Main configs +## GPT-3 models use 2K sequence length/context window +SEQ_LEN=2048 + +### The "GPT-3 XXX" below are configs from GPT-3 paper +### https://arxiv.org/abs/2005.14165, choose based on +### your desired model size or build your own configs + +## GPT-3 Small 125M +MODEL_SIZE=0.125 +NUM_LAYERS=12 +HIDDEN_SIZE=768 +NUM_ATTN_HEADS=12 +# GLOBAL_BATCH_SIZE=256 +# LR=6.0e-4 +MIN_LR=6.0e-5 + +# Curriculum learning (CL) enables stable large-batch training +GLOBAL_BATCH_SIZE=2048 # 8x +LR=2.4e-3 # 4x + +## GPT-3 Medium 350M +# MODEL_SIZE=0.35 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1024 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=3.0e-4 +# MIN_LR=3.0e-5 + +## GPT-3 Large 760M +# MODEL_SIZE=0.76 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1536 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=2.5e-4 +# MIN_LR=2.5e-5 + +## GPT-3 XL 1.3B +# MODEL_SIZE=1.3 +# NUM_LAYERS=24 +# HIDDEN_SIZE=2048 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=512 +# LR=2.0e-4 +# MIN_LR=2.0e-5 + +## GPT-3 2.7B +# MODEL_SIZE=2.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=2560 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=512 +# LR=1.6e-4 +# MIN_LR=1.6e-5 + +## GPT-3 6.7B +# MODEL_SIZE=6.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=4096 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.2e-4 +# MIN_LR=1.2e-5 + +## GPT-3 13B +# MODEL_SIZE=13 +# NUM_LAYERS=40 +# HIDDEN_SIZE=5120 +# NUM_ATTN_HEADS=40 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.0e-4 +# MIN_LR=1.0e-5 + +## GPT-3 175B +# MODEL_SIZE=175 +# NUM_LAYERS=96 +# HIDDEN_SIZE=12288 +# NUM_ATTN_HEADS=96 +# GLOBAL_BATCH_SIZE=1536 +# LR=0.6e-4 +# MIN_LR=0.6e-5 +############################################################################### +### Training duration configs +## The main termination condition, original GPT-3 paper trains for 300B tokens +TRAIN_TOKENS=300000000000 + +## TRAIN_SAMPLES is another termination condition and also affect the number of +## data samples to be indexed. Since we want to reach the TRAIN_TOKENS +## above, and techniques like curriculum learning has less token in some samples, +## so we just set this config large enough to make sure we have enough +## processed data and don't terminate by TRAIN_SAMPLES. +TRAIN_SAMPLES=$(( ${TRAIN_TOKENS} * 3 / ${SEQ_LEN} )) + +## Another termination condition in minutes. Set it large enough to avoid +## undesired early termination. +EXIT_DURATION=30000000 +############################################################################### +### LR configs +## LR warmup and decay duration, this token-based config is preferable since +## no need to readjust when the batch size/seqlen is changed. +## Original GPT-3 paper uses 375M warmup tokens and 260B decay tokens. +WARMUP_TOKENS=375000000 +LR_DECAY_TOKENS=260000000000 +############################################################################### +### Parallelism configs +## Micro batch size per GPU +## Make sure that BATCH_SIZE <= GLOBAL_BATCH_SIZE*PP_SIZE*MP_SIZE/NUM_GPUS +BATCH_SIZE=16 + +## Model parallelism, 1 is no MP +MP_SIZE=1 + +## Pipeline parallelism. To disable PP, set PP_SIZE to 1 and NO_PP to true. +PP_SIZE=1 +NO_PP="true" + +## ZeRO stage +ZERO_STAGE=0 + +## Total number of GPUs +NUM_GPUS=$(($(ds_ssh nvidia-smi --query-gpu=name --format=csv,noheader | wc -l)-2)) +NUM_GPUS_PERNODE=$(nvidia-smi --query-gpu=name --format=csv,noheader | wc -l) +NUM_NODE=$(( ${NUM_GPUS} / ${NUM_GPUS_PERNODE} )) +DP_SIZE=$(( ${NUM_GPUS} / ${PP_SIZE} / ${MP_SIZE} )) +############################################################################### +### Curriculum learning (CL) configs +## Enable/disable CL +CL_ENABLED="true" +## Consult the tutorial https://www.deepspeed.ai/tutorials/curriculum-learning/ +## for tuning the following configs +CL_START_SEQLEN=72 +CL_AVG_SEQLEN=$(( (${CL_START_SEQLEN} + ${SEQ_LEN}) / 2 )) +CL_TOKENS=60 +CL_STEP=$(( ${CL_TOKENS} * 1000000000 / (${GLOBAL_BATCH_SIZE} * ${CL_AVG_SEQLEN}) )) +############################################################################### +### Misc configs +LOG_INTERVAL=10 +EVAL_ITERS=10 +EVAL_INTERVAL=100 +SAVE_INTERVAL=1000 + +## Standard deviation for weight initialization. Usually larger model needs +## lower std. We used a heuristic equation of sqrt(1/3/HIDDEN_SIZE) from the +## MT-NLG 530B work (https://arxiv.org/pdf/2201.11990.pdf) +INIT_STD=0.02 + +## Activation checkpointing saves GPU memory, but reduces training speed +ACTIVATION_CHECKPOINT="true" +# ACTIVATION_CHECKPOINT="false" + +## Whether or not log optimizer states (norms, max abs values) to tensorboard. +## This is not required for training and might save GPU memory when turned off. +LOG_OPTIMIZER_STATE="true" +############################################################################### +### Output and data configs +current_time=$(date "+%Y.%m.%d-%H.%M.%S") +host="${HOSTNAME}" +NAME="gpt3-with-pile-${MODEL_SIZE}B-lr-${LR}-minlr-${MIN_LR}-bs-${GLOBAL_BATCH_SIZE}-gpus-${NUM_GPUS}-zero-${ZERO_STAGE}-mp-${MP_SIZE}-pp-${PP_SIZE}" +if [ "${NO_PP}" = "true" ]; then + NAME="${NAME}-no_pp" +fi +if [ "${CL_ENABLED}" = "true" ]; then + NAME="${NAME}-cl-startseqlen-${CL_START_SEQLEN}-step-${CL_STEP}-token-${CL_TOKENS}B" +fi + +LOG_PATH="log/" +TENSORBOARD_PATH="tensorboard/${NAME}_${host}_${current_time}" +CHECKPOINT_PATH="/blob/users/conglli/project/gpt3_with_pile/checkpoint/${NAME}" +mkdir -p ${LOG_PATH} +mkdir -p ${TENSORBOARD_PATH} +mkdir -p ${CHECKPOINT_PATH} + +VOCAB_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-vocab.json +MERGE_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-merges.txt +# Public the Pile dataset, can be downloaded at https://mystic.the-eye.eu/public/AI/pile_neox/ +# For cluster Azure-EastUS-V100-32GB-4, Lab-RR1-V100 +DATA_PATH=/vc_data_blob/users/conglli/the_pile_public_merged_nopreprocessing/pile_text_document +# For cluster Azure-WestUS3-A100 +# DATA_PATH=/blob/data/the_pile_public_merged_nopreprocessing/pile_text_document +############################################################################### +data_options=" \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --data-path ${DATA_PATH} \ + --data-impl mmap" + +megatron_options=" \ + --override-lr-scheduler \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --tensor-model-parallel-size ${MP_SIZE} \ + --init-method-std ${INIT_STD} \ + --lr-decay-tokens ${LR_DECAY_TOKENS} \ + --lr-warmup-tokens ${WARMUP_TOKENS} \ + --micro-batch-size ${BATCH_SIZE} \ + --exit-duration-in-mins ${EXIT_DURATION} \ + --global-batch-size ${GLOBAL_BATCH_SIZE} \ + --num-layers ${NUM_LAYERS} \ + --hidden-size ${HIDDEN_SIZE} \ + --num-attention-heads ${NUM_ATTN_HEADS} \ + --seq-length ${SEQ_LEN} \ + --max-position-embeddings ${SEQ_LEN} \ + --train-tokens ${TRAIN_TOKENS} \ + --train-samples ${TRAIN_SAMPLES} \ + --lr ${LR} \ + --min-lr ${MIN_LR} \ + --lr-decay-style cosine \ + --split 98,2,0 \ + --log-interval ${LOG_INTERVAL} \ + --eval-interval ${EVAL_INTERVAL} \ + --eval-iters ${EVAL_ITERS} \ + --save-interval ${SAVE_INTERVAL} \ + --weight-decay 0.1 \ + --clip-grad 1.0 \ + --hysteresis 2 \ + --num-workers 0 \ + --fp16 \ + --load ${CHECKPOINT_PATH} \ + --save ${CHECKPOINT_PATH} \ + --tensorboard-queue-size 1 \ + --log-timers-to-tensorboard \ + --log-batch-size-to-tensorboard \ + --log-validation-ppl-to-tensorboard \ + --tensorboard-dir ${TENSORBOARD_PATH}" + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +megatron_options="${megatron_options} \ + --checkpoint-activations" +fi + +if [ "${LOG_OPTIMIZER_STATE}" = "true" ]; then +megatron_options="${megatron_options} \ + --log-optimizer-states-to-tensorboard" +fi + +template_json="ds_config_gpt_TEMPLATE.json" +config_json="ds_config_${NAME}.json" +if [[ $ZERO_STAGE -gt 0 ]]; then +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/ZERO_STAGE/${ZERO_STAGE}/" \ + | sed "s/PRESCALE_GRAD/false/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} +else +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/ZERO_STAGE/${ZERO_STAGE}/" \ + | sed "s/PRESCALE_GRAD/true/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} +fi + +deepspeed_options=" \ + --deepspeed \ + --deepspeed_config ${config_json} \ + --zero-stage ${ZERO_STAGE} \ + --pipeline-model-parallel-size ${PP_SIZE}" + +if [[ "${NO_PP}" = "true" ]]; then +deepspeed_options="${deepspeed_options} \ + --no-pipeline-parallel" +fi + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +deepspeed_options="${deepspeed_options} \ + --deepspeed-activation-checkpointing" +fi + +## When saving checkpoint to a storage with cache, their could be consistency +## issue of the pointer to latest checkpoint. Here we find the correct pointer +## and broadcast it to all nodes. +ITERATION_FILE="$CHECKPOINT_PATH/latest_checkpointed_iteration.txt" +ITERATION_FILE_2="$CHECKPOINT_PATH/latest" +ITERATION=0 +for (( node = 0; node <= NUM_NODE-1; node++ )) +do + if $(ssh -q worker-"$node" "test -f \"$ITERATION_FILE\""); then + LOCAL_ITERATION=$(ssh -q worker-"$node" cat $ITERATION_FILE) + ITERATION=$(( ${LOCAL_ITERATION} > ${ITERATION} ? ${LOCAL_ITERATION} : ${ITERATION} )) + fi +done +if [[ $ITERATION -gt 0 ]]; then + ITERATION_2="global_step${ITERATION}" + ds_ssh "echo $ITERATION > $ITERATION_FILE" + ds_ssh "echo $ITERATION_2 > $ITERATION_FILE_2" +fi + +run_cmd="deepspeed ${DIR}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &> ${LOG_PATH}/${NAME}_${host}_${current_time}.log" +echo ${run_cmd} +eval ${run_cmd} +set +x diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_350M_MoE128.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_350M_MoE128.sh new file mode 100644 index 0000000000000000000000000000000000000000..7ccfe7f45a4b15e5598ab0becfedb4bd4ee766f0 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_350M_MoE128.sh @@ -0,0 +1,349 @@ +#!/bin/bash +DIR=`pwd` +############################################################################### +### Main configs +## GPT-3 models use 2K sequence length/context window +SEQ_LEN=2048 + +### The "GPT-3 XXX" below are configs from GPT-3 paper +### https://arxiv.org/abs/2005.14165, choose based on +### your desired model size or build your own configs + +## GPT-3 Small 125M +# MODEL_SIZE=0.125 +# NUM_LAYERS=12 +# HIDDEN_SIZE=768 +# NUM_ATTN_HEADS=12 +# GLOBAL_BATCH_SIZE=256 +# LR=6.0e-4 +# MIN_LR=6.0e-5 + +## GPT-3 Medium 350M +MODEL_SIZE=0.35 +NUM_LAYERS=24 +HIDDEN_SIZE=1024 +NUM_ATTN_HEADS=16 +GLOBAL_BATCH_SIZE=256 +# LR=3.0e-4 +# MIN_LR=3.0e-5 + +## GPT-3 Large 760M +# MODEL_SIZE=0.76 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1536 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=2.5e-4 +# MIN_LR=2.5e-5 + +## GPT-3 XL 1.3B +# MODEL_SIZE=1.3 +# NUM_LAYERS=24 +# HIDDEN_SIZE=2048 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=512 +# LR=2.0e-4 +# MIN_LR=2.0e-5 + +## GPT-3 2.7B +# MODEL_SIZE=2.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=2560 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=512 +# LR=1.6e-4 +# MIN_LR=1.6e-5 + +## GPT-3 6.7B +# MODEL_SIZE=6.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=4096 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.2e-4 +# MIN_LR=1.2e-5 + +## GPT-3 13B +# MODEL_SIZE=13 +# NUM_LAYERS=40 +# HIDDEN_SIZE=5120 +# NUM_ATTN_HEADS=40 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.0e-4 +# MIN_LR=1.0e-5 + +## GPT-3 175B +# MODEL_SIZE=175 +# NUM_LAYERS=96 +# HIDDEN_SIZE=12288 +# NUM_ATTN_HEADS=96 +# GLOBAL_BATCH_SIZE=1536 +# LR=0.6e-4 +# MIN_LR=0.6e-5 +############################################################################### +### Training duration configs +## The main termination condition, original GPT-3 paper trains for 300B tokens +## For MoE model, we found sometimes training a bit more to 330B tokens helps +TRAIN_TOKENS=300000000000 +# TRAIN_TOKENS=330000000000 + +## TRAIN_ITERS is another termination condition and also affect the number of +## data samples to be indexed. Since we want to reach the TRAIN_TOKENS +## above, and techniques like curriculum learning has less token in some steps, +## so we just set this config large enough to make sure we have enough +## processed data and don't terminate by TRAIN_ITERS. +TRAIN_ITERS=$(( ${TRAIN_TOKENS} * 3 / ${GLOBAL_BATCH_SIZE} / ${SEQ_LEN} )) + +## Another termination condition in minutes. Set it large enough to avoid +## undesired early termination. +EXIT_DURATION=30000000 +############################################################################### +### LR configs +## LR warmup and decay duration, this token-based config is preferable since +## no need to readjust when the batch size/seqlen is changed. +## Original GPT-3 paper uses 375M warmup tokens and 260B decay tokens. +## For MoE model, we found that setting the decay token to 300B helps. +WARMUP_TOKENS=375000000 +# LR_DECAY_TOKENS=260000000000 +LR_DECAY_TOKENS=300000000000 +############################################################################### +### Parallelism configs +## Micro batch size per GPU +## Make sure that BATCH_SIZE <= GLOBAL_BATCH_SIZE*PP_SIZE*MP_SIZE/NUM_GPUS +BATCH_SIZE=4 + +## Model parallelism, 1 is no MP +## Currently MoE models have divergence issue when MP > 1. +MP_SIZE=1 + +## Pipeline parallelism +## Currently we don't support PP for MoE. To disable PP, set PP_SIZE +## to 1 and use the "--no-pipeline-parallel" arg. +PP_SIZE=1 +NUM_GPUS=64 +############################################################################### +### MoE configs +## Number of experts. EP_SIZE 1 means dense model without MoE +# EP_SIZE=1 +EP_SIZE=128 + +if [[ $EP_SIZE -gt $NUM_GPUS ]]; then + EP_PARALLEL_SIZE=$NUM_GPUS +else + EP_PARALLEL_SIZE=$EP_SIZE +fi + +## Original GPT-3 model always set min LR at 10% of max LR. For MoE model, we +## found that lower LR and min LR (than the base dense model) helps. +## For 1.3B MoE-128 model we used LR=1.2e-4 and MIN_LR=1.0e-6. +## For 350M MoE-128 model we used LR=2.0e-4 and MIN_LR=2.0e-6, but they are not +## heavily tuned. +LR=2.0e-4 +MIN_LR=2e-06 + +## Coefficient for MoE loss. We find that 0.01 is a good value at least for +## 1.3B MoE-128 model +MLC=0.01 + +## Below configs adjust the MoE expert token capacity limit during training and +## eval. To completely disable capacity limit, set MOE_DROP_TOKEN to false. +## Larger capacity factor or disabling capacity limit could improve training +## convergence, but will also reduce training throughput. +MOE_TRAIN_CAP_FACTOR=1.0 +MOE_EVAL_CAP_FACTOR=1.0 +MOE_MIN_CAP=4 +MOE_DROP_TOKEN="true" +# MOE_DROP_TOKEN="false" +############################################################################### +### Curriculum learning (CL) configs +## Enable/disable CL +CL_ENABLED="false" +## Consult the tutorial https://www.deepspeed.ai/tutorials/curriculum-learning/ +## for tuning the following configs +CL_START_SEQLEN=80 +CL_AVG_SEQLEN=$(( (${CL_START_SEQLEN} + ${SEQ_LEN}) / 2 )) +CL_TOKENS=60 +CL_TOKENS=$((${CL_TOKENS} * 1000000000)) +CL_STEP=$(( ${CL_TOKENS} / (${GLOBAL_BATCH_SIZE} * ${CL_AVG_SEQLEN}) )) +############################################################################### +### Misc configs +LOG_INTERVAL=10 +EVAL_ITERS=10 +EVAL_INTERVAL=100 +SAVE_INTERVAL=10000 + +## Standard deviation for weight initialization +## We used 0.014 for 350M/1.3B dense/MoE models, and used 0.01 for 6.7B +## dense model. Usually larger model needs lower std. +INIT_STD=0.014 +# INIT_STD=0.01 + +## Activation checkpointing saves GPU memory, but reduces training speed +ACTIVATION_CHECKPOINT="true" +# ACTIVATION_CHECKPOINT="false" +############################################################################### +### Output and data configs +current_time=$(date "+%Y.%m.%d-%H.%M.%S") +host="${HOSTNAME}" +NAME="gpt-${MODEL_SIZE}B-lr-${LR}-minlr-${MIN_LR}-bs-${GLOBAL_BATCH_SIZE}-gpus-${NUM_GPUS}-mp-${MP_SIZE}-pp-${PP_SIZE}" +if [[ $EP_SIZE -gt 1 ]]; then + NAME="${NAME}-ep-${EP_SIZE}-mlc-${MLC}-cap-${MOE_TRAIN_CAP_FACTOR}-drop-${MOE_DROP_TOKEN}" +fi +if [ "${CL_ENABLED}" = "true" ]; then + NAME="${NAME}-cl-${CL_START_SEQLEN}-${CL_STEP}" +fi + +OUTPUT_BASEPATH=$DIR/output +mkdir -p "${OUTPUT_BASEPATH}/tensorboard/" +mkdir -p "${OUTPUT_BASEPATH}/checkpoint/" +mkdir -p "${OUTPUT_BASEPATH}/log/" +TENSORBOARD_DIR="${OUTPUT_BASEPATH}/tensorboard/${NAME}_${host}_${current_time}" +mkdir -p ${TENSORBOARD_DIR} +## Note that for MoE model with billion-scale base model, the checkpoint can be +## as large as TB-scale which normal NFS cannot handle efficiently. +CHECKPOINT_PATH="${OUTPUT_BASEPATH}/checkpoint/${NAME}" + +# USE_INTERNAL_DATA="true" +USE_INTERNAL_DATA="false" + +if [ "${USE_INTERNAL_DATA}" = "true" ]; then + ## The internal data is only accessible within Microsoft + ## For cluster Azure-EastUS-V100-32GB-4, Azure-WestUS3-A100 + # BASE_DATA_PATH=/vc_data/Megatron-LM/data + # DATA_HOME="/vc_data/pile-cc1-cc2-shuf" + ## For cluster Lab-RR1-V100 + BASE_DATA_PATH=/data/Megatron-LM/data + DATA_HOME="/turing-ssd/users/conglli/data/pile-cc1-cc2-shuf" + ## For cluster Azure-CentralUS-A100 + # BASE_DATA_PATH=/data/Megatron-LM/data + # DATA_HOME=/vc_data_1/users/amawa/blended + + VOCAB_PATH=${BASE_DATA_PATH}/gpt2-vocab.json + MERGE_PATH=${BASE_DATA_PATH}/gpt2-merges.txt + ARX="${DATA_HOME}/ArXiv_ftfy_cleaned_id_shuf_text_document" + BC2="${DATA_HOME}/BookCorpus2_ftfy_cleaned_id_shuf_text_document" + B3="${DATA_HOME}/Books3_ftfy_cleaned_id_shuf_text_document" + CC2020="${DATA_HOME}/CC-2020-50_id_cleaned_shuf_text_document" + CC2021="${DATA_HOME}/CC-2021-04_id_cleaned_shuf_text_document" + GIT="${DATA_HOME}/Github_ftfy_id_shuf_text_document" + GUT="${DATA_HOME}/Gutenberg_PG-19_ftfy_cleaned_id_cleaned_shuf_text_document" + NIH="${DATA_HOME}/NIH_ExPorter_ftfy_id_shuf_text_document" + OWT2="${DATA_HOME}/OpenWebText2_ftfy_cleaned_id_shuf_text_document" + PCC="${DATA_HOME}/Pile-CC_id_cleaned_shuf_text_document" + PM="${DATA_HOME}/PubMed_Abstracts_ftfy_id_shuf_text_document" + RN="${DATA_HOME}/rn_dedup_shuf_cleaned_0.7_cleaned_shuf_text_document" + SE="${DATA_HOME}/StackExchange_ftfy_id_shuf_text_document" + ST="${DATA_HOME}/stories_dedup0.7_shuf_cleaned_shuf_text_document" + WIK="${DATA_HOME}/Wikipedia_en_ftfy_id_shuf_text_document" + DATA_BLEND="0.14336 ${B3} 0.08962 ${RN} 0.19336 ${OWT2} 0.05689 ${SE} \ + 0.00859 ${ST} 0.02897 ${PM} 0.04771 ${WIK} 0.00873 ${GUT} 0.01007 ${BC2} \ + 0.00208 ${NIH} 0.13017 ${CC2020} 0.09446 ${PCC} 0.15652 ${CC2021} \ + 0.01359 ${ARX} 0.01588 ${GIT}" +else + VOCAB_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-vocab.json + MERGE_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-merges.txt + # Public the Pile dataset, can be downloaded at https://mystic.the-eye.eu/public/AI/pile_neox/ + DATA_BLEND=/data/the_pile_public_merged_nopreprocessing/pile_text_document +fi +############################################################################### +data_options=" \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --data-path ${DATA_BLEND} \ + --data-impl mmap" + +megatron_options=" \ + --override-lr-scheduler \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --tensor-model-parallel-size ${MP_SIZE} \ + --moe-expert-parallel-size ${EP_PARALLEL_SIZE} \ + --num-experts ${EP_SIZE} \ + --moe-loss-coeff ${MLC} \ + --moe-train-capacity-factor ${MOE_TRAIN_CAP_FACTOR} \ + --moe-eval-capacity-factor ${MOE_EVAL_CAP_FACTOR} \ + --moe-min-capacity ${MOE_MIN_CAP} \ + --init-method-std ${INIT_STD} \ + --lr-decay-tokens ${LR_DECAY_TOKENS} \ + --lr-warmup-tokens ${WARMUP_TOKENS} \ + --micro-batch-size ${BATCH_SIZE} \ + --exit-duration-in-mins ${EXIT_DURATION} \ + --global-batch-size ${GLOBAL_BATCH_SIZE} \ + --num-layers ${NUM_LAYERS} \ + --hidden-size ${HIDDEN_SIZE} \ + --num-attention-heads ${NUM_ATTN_HEADS} \ + --seq-length ${SEQ_LEN} \ + --max-position-embeddings ${SEQ_LEN} \ + --train-tokens ${TRAIN_TOKENS} \ + --train-iters ${TRAIN_ITERS} \ + --lr ${LR} \ + --min-lr ${MIN_LR} \ + --lr-decay-style cosine \ + --split 98,2,0 \ + --log-interval ${LOG_INTERVAL} \ + --eval-interval ${EVAL_INTERVAL} \ + --eval-iters ${EVAL_ITERS} \ + --save-interval ${SAVE_INTERVAL} \ + --weight-decay 0.1 \ + --clip-grad 1.0 \ + --hysteresis 2 \ + --num-workers 0 \ + --fp16 \ + --load ${CHECKPOINT_PATH} \ + --save ${CHECKPOINT_PATH} \ + --tensorboard-queue-size 1 \ + --log-timers-to-tensorboard \ + --log-batch-size-to-tensorboard \ + --log-validation-ppl-to-tensorboard \ + --tensorboard-dir ${TENSORBOARD_DIR}" + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +megatron_options="${megatron_options} \ + --checkpoint-activations" +fi + +if [[ $EP_SIZE -gt 1 ]]; then +megatron_options="${megatron_options} \ + --create-moe-param-group" +fi + +if [ "${MOE_DROP_TOKEN}" = "false" ]; then +megatron_options="${megatron_options} \ + --disable-moe-token-dropping" +fi + +template_json="ds_config_gpt_TEMPLATE.json" +config_json="ds_config_gpt_${NAME}.json" +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/ZERO_STAGE/0/" \ + | sed "s/PRESCALE_GRAD/true/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} + +deepspeed_options=" \ + --deepspeed \ + --deepspeed_config ${config_json} \ + --pipeline-model-parallel-size ${PP_SIZE}" + +# Currently MoE is not compatible with pipeline parallel +if [[ $EP_SIZE -gt 1 ]]; then +deepspeed_options="${deepspeed_options} \ + --no-pipeline-parallel" +fi + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +deepspeed_options="${deepspeed_options} \ + --deepspeed-activation-checkpointing" +fi + +run_cmd="deepspeed ${DIR}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &> ${OUTPUT_BASEPATH}/log/${NAME}_${host}_${current_time}.log" +echo ${run_cmd} +eval ${run_cmd} +set +x diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_350M_PR-MoE32or64.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_350M_PR-MoE32or64.sh new file mode 100644 index 0000000000000000000000000000000000000000..cc4a7d1128823e705f339cf3f4189559f65f2922 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_350M_PR-MoE32or64.sh @@ -0,0 +1,342 @@ +#!/bin/bash +DIR=`pwd` +############################################################################### +### Main configs +## GPT-3 models use 2K sequence length/context window +SEQ_LEN=2048 + +### The "GPT-3 XXX" below are configs from GPT-3 paper +### https://arxiv.org/abs/2005.14165, choose based on +### your desired model size or build your own configs + +## GPT-3 Small 125M +# MODEL_SIZE=0.125 +# NUM_LAYERS=12 +# HIDDEN_SIZE=768 +# NUM_ATTN_HEADS=12 +# GLOBAL_BATCH_SIZE=256 +# LR=6.0e-4 +# MIN_LR=6.0e-5 + +## GPT-3 Medium 350M +MODEL_SIZE=0.35 +NUM_LAYERS=24 +HIDDEN_SIZE=1024 +NUM_ATTN_HEADS=16 +GLOBAL_BATCH_SIZE=256 +# LR=3.0e-4 +# MIN_LR=3.0e-5 + +## GPT-3 Large 760M +# MODEL_SIZE=0.76 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1536 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=2.5e-4 +# MIN_LR=2.5e-5 + +## GPT-3 XL 1.3B +# MODEL_SIZE=1.3 +# NUM_LAYERS=24 +# HIDDEN_SIZE=2048 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=512 +# LR=2.0e-4 +# MIN_LR=2.0e-5 + +## GPT-3 2.7B +# MODEL_SIZE=2.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=2560 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=512 +# LR=1.6e-4 +# MIN_LR=1.6e-5 + +## GPT-3 6.7B +# MODEL_SIZE=6.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=4096 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.2e-4 +# MIN_LR=1.2e-5 + +## GPT-3 13B +# MODEL_SIZE=13 +# NUM_LAYERS=40 +# HIDDEN_SIZE=5120 +# NUM_ATTN_HEADS=40 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.0e-4 +# MIN_LR=1.0e-5 + +## GPT-3 175B +# MODEL_SIZE=175 +# NUM_LAYERS=96 +# HIDDEN_SIZE=12288 +# NUM_ATTN_HEADS=96 +# GLOBAL_BATCH_SIZE=1536 +# LR=0.6e-4 +# MIN_LR=0.6e-5 +############################################################################### +### Training duration configs +## The main termination condition, original GPT-3 paper trains for 300B tokens +## For MoE model, we found sometimes training a bit more to 330B tokens helps +TRAIN_TOKENS=300000000000 +# TRAIN_TOKENS=330000000000 + +## TRAIN_ITERS is another termination condition and also affect the number of +## data samples to be indexed. Since we want to reach the TRAIN_TOKENS +## above, and techniques like curriculum learning has less token in some steps, +## so we just set this config large enough to make sure we have enough +## processed data and don't terminate by TRAIN_ITERS. +TRAIN_ITERS=$(( ${TRAIN_TOKENS} * 3 / ${GLOBAL_BATCH_SIZE} / ${SEQ_LEN} )) + +## Another termination condition in minutes. Set it large enough to avoid +## undesired early termination. +EXIT_DURATION=30000000 +############################################################################### +### LR configs +## LR warmup and decay duration, this token-based config is preferable since +## no need to readjust when the batch size/seqlen is changed. +## Original GPT-3 paper uses 375M warmup tokens and 260B decay tokens. +## For MoE model, we found that setting the decay token to 300B helps. +WARMUP_TOKENS=375000000 +# LR_DECAY_TOKENS=260000000000 +LR_DECAY_TOKENS=300000000000 +############################################################################### +### Parallelism configs +## Micro batch size per GPU +## Make sure that BATCH_SIZE <= GLOBAL_BATCH_SIZE*PP_SIZE*MP_SIZE/NUM_GPUS +BATCH_SIZE=4 + +## Model parallelism, 1 is no MP +## Currently MoE models have divergence issue when MP > 1. +MP_SIZE=1 + +## Pipeline parallelism +## Currently we don't support PP for MoE. To disable PP, set PP_SIZE +## to 1 and use the "--no-pipeline-parallel" arg. +PP_SIZE=1 +NUM_GPUS=64 +############################################################################### +### MoE configs +## Number of experts. EP_SIZE 128 means standard MoE +# EP_SIZE=128 +EP_SIZE="32 32 32 32 32 32 32 32 32 32 64 64" + +EP_PARALLEL_SIZE=$NUM_GPUS + +## Original GPT-3 model always set min LR at 10% of max LR. For MoE model, we +## found that lower LR and min LR (than the base dense model) helps. +## For 1.3B PR-MoE-64/128 model we used LR=1.2e-4 and MIN_LR=1.0e-6. +## For 350M PR-MoE-32/64 model we used LR=3.0e-4 and MIN_LR=1.0e-6, but they are not +## heavily tuned. +LR=3.0e-4 +MIN_LR=1.0e-06 + +## Coefficient for MoE loss. We find that 0.01 is a good value at least for +## 1.3B MoE-128 model +MLC=0.01 + +## Below configs adjust the MoE expert token capacity limit during training and +## eval. To completely disable capacity limit, set MOE_DROP_TOKEN to false. +## Larger capacity factor or disabling capacity limit could improve training +## convergence, but will also reduce training throughput. +MOE_TRAIN_CAP_FACTOR=1.0 +MOE_EVAL_CAP_FACTOR=1.0 +MOE_MIN_CAP=4 +MOE_DROP_TOKEN="true" +# MOE_DROP_TOKEN="false" +############################################################################### +### Curriculum learning (CL) configs +## Enable/disable CL +CL_ENABLED="false" +## Consult the tutorial https://www.deepspeed.ai/tutorials/curriculum-learning/ +## for tuning the following configs +CL_START_SEQLEN=80 +CL_AVG_SEQLEN=$(( (${CL_START_SEQLEN} + ${SEQ_LEN}) / 2 )) +CL_TOKENS=60 +CL_TOKENS=$((${CL_TOKENS} * 1000000000)) +CL_STEP=$(( ${CL_TOKENS} / (${GLOBAL_BATCH_SIZE} * ${CL_AVG_SEQLEN}) )) +############################################################################### +### Misc configs +LOG_INTERVAL=10 +EVAL_ITERS=10 +EVAL_INTERVAL=100 +SAVE_INTERVAL=10000 + +## Standard deviation for weight initialization +## We used 0.014 for 350M/1.3B dense/MoE models, and used 0.01 for 6.7B +## dense model. Usually larger model needs lower std. +INIT_STD=0.014 +# INIT_STD=0.01 + +## Activation checkpointing saves GPU memory, but reduces training speed +ACTIVATION_CHECKPOINT="true" +# ACTIVATION_CHECKPOINT="false" +############################################################################### +### Output and data configs +current_time=$(date "+%Y.%m.%d-%H.%M.%S") +host="${HOSTNAME}" +NAME="gpt-${MODEL_SIZE}B-lr-${LR}-minlr-${MIN_LR}-bs-${GLOBAL_BATCH_SIZE}-gpus-${NUM_GPUS}-mp-${MP_SIZE}-pp-${PP_SIZE}" +NAME="${NAME}-ep-pyramid-32+64-mlc-${MLC}-cap-${MOE_TRAIN_CAP_FACTOR}-drop-${MOE_DROP_TOKEN}" + +if [ "${CL_ENABLED}" = "true" ]; then + NAME="${NAME}-cl-${CL_START_SEQLEN}-${CL_STEP}" +fi + +OUTPUT_BASEPATH=$DIR/output +mkdir -p "${OUTPUT_BASEPATH}/tensorboard/" +mkdir -p "${OUTPUT_BASEPATH}/checkpoint/" +mkdir -p "${OUTPUT_BASEPATH}/log/" +TENSORBOARD_DIR="${OUTPUT_BASEPATH}/tensorboard/${NAME}_${host}_${current_time}" +mkdir -p ${TENSORBOARD_DIR} +## Note that for MoE model with billion-scale base model, the checkpoint can be +## as large as TB-scale which normal NFS cannot handle efficiently. +CHECKPOINT_PATH="${OUTPUT_BASEPATH}/checkpoint/${NAME}" + +# USE_INTERNAL_DATA="true" +USE_INTERNAL_DATA="false" + +if [ "${USE_INTERNAL_DATA}" = "true" ]; then + ## The internal data is only accessible within Microsoft + ## For cluster Azure-EastUS-V100-32GB-4, Azure-WestUS3-A100 + BASE_DATA_PATH=/vc_data/Megatron-LM/data + DATA_HOME="/vc_data/pile-cc1-cc2-shuf" + ## For cluster Lab-RR1-V100 + # BASE_DATA_PATH=/data/Megatron-LM/data + # DATA_HOME="/turing-ssd/users/conglli/data/pile-cc1-cc2-shuf" + ## For cluster Azure-CentralUS-A100 + # BASE_DATA_PATH=/data/Megatron-LM/data + # DATA_HOME=/vc_data_1/users/amawa/blended + + VOCAB_PATH=${BASE_DATA_PATH}/gpt2-vocab.json + MERGE_PATH=${BASE_DATA_PATH}/gpt2-merges.txt + ARX="${DATA_HOME}/ArXiv_ftfy_cleaned_id_shuf_text_document" + BC2="${DATA_HOME}/BookCorpus2_ftfy_cleaned_id_shuf_text_document" + B3="${DATA_HOME}/Books3_ftfy_cleaned_id_shuf_text_document" + CC2020="${DATA_HOME}/CC-2020-50_id_cleaned_shuf_text_document" + CC2021="${DATA_HOME}/CC-2021-04_id_cleaned_shuf_text_document" + GIT="${DATA_HOME}/Github_ftfy_id_shuf_text_document" + GUT="${DATA_HOME}/Gutenberg_PG-19_ftfy_cleaned_id_cleaned_shuf_text_document" + NIH="${DATA_HOME}/NIH_ExPorter_ftfy_id_shuf_text_document" + OWT2="${DATA_HOME}/OpenWebText2_ftfy_cleaned_id_shuf_text_document" + PCC="${DATA_HOME}/Pile-CC_id_cleaned_shuf_text_document" + PM="${DATA_HOME}/PubMed_Abstracts_ftfy_id_shuf_text_document" + RN="${DATA_HOME}/rn_dedup_shuf_cleaned_0.7_cleaned_shuf_text_document" + SE="${DATA_HOME}/StackExchange_ftfy_id_shuf_text_document" + ST="${DATA_HOME}/stories_dedup0.7_shuf_cleaned_shuf_text_document" + WIK="${DATA_HOME}/Wikipedia_en_ftfy_id_shuf_text_document" + DATA_BLEND="0.14336 ${B3} 0.08962 ${RN} 0.19336 ${OWT2} 0.05689 ${SE} \ + 0.00859 ${ST} 0.02897 ${PM} 0.04771 ${WIK} 0.00873 ${GUT} 0.01007 ${BC2} \ + 0.00208 ${NIH} 0.13017 ${CC2020} 0.09446 ${PCC} 0.15652 ${CC2021} \ + 0.01359 ${ARX} 0.01588 ${GIT}" +else + VOCAB_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-vocab.json + MERGE_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-merges.txt + # Public the Pile dataset, can be downloaded at https://mystic.the-eye.eu/public/AI/pile_neox/ + DATA_BLEND=/data/the_pile_public_merged_nopreprocessing/pile_text_document +fi +############################################################################### +data_options=" \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --data-path ${DATA_BLEND} \ + --data-impl mmap" + +megatron_options=" \ + --override-lr-scheduler \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --tensor-model-parallel-size ${MP_SIZE} \ + --moe-expert-parallel-size ${EP_PARALLEL_SIZE} \ + --num-experts ${EP_SIZE} \ + --moe-loss-coeff ${MLC} \ + --mlp-type residual \ + --moe-train-capacity-factor ${MOE_TRAIN_CAP_FACTOR} \ + --moe-eval-capacity-factor ${MOE_EVAL_CAP_FACTOR} \ + --moe-min-capacity ${MOE_MIN_CAP} \ + --init-method-std ${INIT_STD} \ + --lr-decay-tokens ${LR_DECAY_TOKENS} \ + --lr-warmup-tokens ${WARMUP_TOKENS} \ + --micro-batch-size ${BATCH_SIZE} \ + --exit-duration-in-mins ${EXIT_DURATION} \ + --global-batch-size ${GLOBAL_BATCH_SIZE} \ + --num-layers ${NUM_LAYERS} \ + --hidden-size ${HIDDEN_SIZE} \ + --num-attention-heads ${NUM_ATTN_HEADS} \ + --seq-length ${SEQ_LEN} \ + --max-position-embeddings ${SEQ_LEN} \ + --train-tokens ${TRAIN_TOKENS} \ + --train-iters ${TRAIN_ITERS} \ + --lr ${LR} \ + --min-lr ${MIN_LR} \ + --lr-decay-style cosine \ + --split 98,2,0 \ + --log-interval ${LOG_INTERVAL} \ + --eval-interval ${EVAL_INTERVAL} \ + --eval-iters ${EVAL_ITERS} \ + --save-interval ${SAVE_INTERVAL} \ + --weight-decay 0.1 \ + --clip-grad 1.0 \ + --hysteresis 2 \ + --num-workers 0 \ + --fp16 \ + --load ${CHECKPOINT_PATH} \ + --save ${CHECKPOINT_PATH} \ + --tensorboard-queue-size 1 \ + --log-timers-to-tensorboard \ + --log-batch-size-to-tensorboard \ + --log-validation-ppl-to-tensorboard \ + --tensorboard-dir ${TENSORBOARD_DIR}" + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +megatron_options="${megatron_options} \ + --checkpoint-activations" +fi + +megatron_options="${megatron_options} \ + --create-moe-param-group" + +if [ "${MOE_DROP_TOKEN}" = "false" ]; then +megatron_options="${megatron_options} \ + --disable-moe-token-dropping" +fi + +template_json="ds_config_gpt_TEMPLATE.json" +config_json="ds_config_gpt_${NAME}.json" +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/ZERO_STAGE/0/" \ + | sed "s/PRESCALE_GRAD/true/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} + +deepspeed_options=" \ + --deepspeed \ + --deepspeed_config ${config_json} \ + --pipeline-model-parallel-size ${PP_SIZE}" + +# Currently MoE is not compatible with pipeline parallel +deepspeed_options="${deepspeed_options} \ + --no-pipeline-parallel" + + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +deepspeed_options="${deepspeed_options} \ + --deepspeed-activation-checkpointing" +fi + +run_cmd="deepspeed ${DIR}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &> ${OUTPUT_BASEPATH}/log/${NAME}_${host}_${current_time}.log" +echo ${run_cmd} +eval ${run_cmd} +set +x diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_350M_PR-MoE32or64_MoS.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_350M_PR-MoE32or64_MoS.sh new file mode 100644 index 0000000000000000000000000000000000000000..d8ee844dfc52d282b4ed732ab84c39a3946f1308 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_350M_PR-MoE32or64_MoS.sh @@ -0,0 +1,354 @@ +#!/bin/bash +DIR=`pwd` +############################################################################### +### Main configs +## GPT-3 models use 2K sequence length/context window +SEQ_LEN=2048 + +### The "GPT-3 XXX" below are configs from GPT-3 paper +### https://arxiv.org/abs/2005.14165, choose based on +### your desired model size or build your own configs + +## GPT-3 Small 125M +# MODEL_SIZE=0.125 +# NUM_LAYERS=12 +# HIDDEN_SIZE=768 +# NUM_ATTN_HEADS=12 +# GLOBAL_BATCH_SIZE=256 +# LR=6.0e-4 +# MIN_LR=6.0e-5 + +## GPT-3 Medium 350M +MODEL_SIZE=0.35 +NUM_LAYERS=24 +HIDDEN_SIZE=1024 +NUM_ATTN_HEADS=16 +GLOBAL_BATCH_SIZE=256 +# LR=3.0e-4 +# MIN_LR=3.0e-5 + +## GPT-3 Large 760M +# MODEL_SIZE=0.76 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1536 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=2.5e-4 +# MIN_LR=2.5e-5 + +## GPT-3 XL 1.3B +# MODEL_SIZE=1.3 +# NUM_LAYERS=24 +# HIDDEN_SIZE=2048 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=512 +# LR=2.0e-4 +# MIN_LR=2.0e-5 + +## GPT-3 2.7B +# MODEL_SIZE=2.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=2560 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=512 +# LR=1.6e-4 +# MIN_LR=1.6e-5 + +## GPT-3 6.7B +# MODEL_SIZE=6.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=4096 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.2e-4 +# MIN_LR=1.2e-5 + +## GPT-3 13B +# MODEL_SIZE=13 +# NUM_LAYERS=40 +# HIDDEN_SIZE=5120 +# NUM_ATTN_HEADS=40 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.0e-4 +# MIN_LR=1.0e-5 + +## GPT-3 175B +# MODEL_SIZE=175 +# NUM_LAYERS=96 +# HIDDEN_SIZE=12288 +# NUM_ATTN_HEADS=96 +# GLOBAL_BATCH_SIZE=1536 +# LR=0.6e-4 +# MIN_LR=0.6e-5 +############################################################################### +### Training duration configs +## The main termination condition, original GPT-3 paper trains for 300B tokens +## For MoE model, we found sometimes training a bit more to 330B tokens helps +TRAIN_TOKENS=300000000000 +# TRAIN_TOKENS=330000000000 + +## TRAIN_ITERS is another termination condition and also affect the number of +## data samples to be indexed. Since we want to reach the TRAIN_TOKENS +## above, and techniques like curriculum learning has less token in some steps, +## so we just set this config large enough to make sure we have enough +## processed data and don't terminate by TRAIN_ITERS. +TRAIN_ITERS=$(( ${TRAIN_TOKENS} * 3 / ${GLOBAL_BATCH_SIZE} / ${SEQ_LEN} )) + +## Another termination condition in minutes. Set it large enough to avoid +## undesired early termination. +EXIT_DURATION=30000000 +############################################################################### +### LR configs +## LR warmup and decay duration, this token-based config is preferable since +## no need to readjust when the batch size/seqlen is changed. +## Original GPT-3 paper uses 375M warmup tokens and 260B decay tokens. +## For MoE model, we found that setting the decay token to 300B helps. +WARMUP_TOKENS=375000000 +# LR_DECAY_TOKENS=260000000000 +LR_DECAY_TOKENS=300000000000 +############################################################################### +### Parallelism configs +## Micro batch size per GPU +## Make sure that BATCH_SIZE <= GLOBAL_BATCH_SIZE*PP_SIZE*MP_SIZE/NUM_GPUS +BATCH_SIZE=4 + +## Model parallelism, 1 is no MP +## Currently MoE models have divergence issue when MP > 1. +MP_SIZE=1 + +## Pipeline parallelism +## Currently we don't support PP for MoE. To disable PP, set PP_SIZE +## to 1 and use the "--no-pipeline-parallel" arg. +PP_SIZE=1 +NUM_GPUS=64 +############################################################################### +### MoE configs +## Number of experts. EP_SIZE 128 means standard MoE +# EP_SIZE=128 +EP_SIZE="32 32 32 32 32 32 32 32 64 64" +EP_SIZE_TEACHER="32 32 32 32 32 32 32 32 32 32 64 64" + +EP_PARALLEL_SIZE=$NUM_GPUS + +## Original GPT-3 model always set min LR at 10% of max LR. For MoE model, we +## found that lower LR and min LR (than the base dense model) helps. +## For 1.3B PR-MoE-64/128 model we used LR=1.2e-4 and MIN_LR=1.0e-6. +## For 350M PR-MoE-32/64 model we used LR=3.0e-4 and MIN_LR=1.0e-6, but they are not +## heavily tuned. +LR=3.0e-4 +MIN_LR=1.0e-06 + +## Coefficient for MoE loss. We find that 0.01 is a good value at least for +## 1.3B MoE-128 model +MLC=0.01 + +## Below configs adjust the MoE expert token capacity limit during training and +## eval. To completely disable capacity limit, set MOE_DROP_TOKEN to false. +## Larger capacity factor or disabling capacity limit could improve training +## convergence, but will also reduce training throughput. +MOE_TRAIN_CAP_FACTOR=1.0 +MOE_EVAL_CAP_FACTOR=1.0 +MOE_MIN_CAP=4 +MOE_DROP_TOKEN="true" +# MOE_DROP_TOKEN="false" +############################################################################### +### Curriculum learning (CL) configs +## Enable/disable CL +CL_ENABLED="false" +## Consult the tutorial https://www.deepspeed.ai/tutorials/curriculum-learning/ +## for tuning the following configs +CL_START_SEQLEN=80 +CL_AVG_SEQLEN=$(( (${CL_START_SEQLEN} + ${SEQ_LEN}) / 2 )) +CL_TOKENS=60 +CL_TOKENS=$((${CL_TOKENS} * 1000000000)) +CL_STEP=$(( ${CL_TOKENS} / (${GLOBAL_BATCH_SIZE} * ${CL_AVG_SEQLEN}) )) +############################################################################### +### Misc configs +LOG_INTERVAL=10 +EVAL_ITERS=10 +EVAL_INTERVAL=100 +SAVE_INTERVAL=10000 + +## Standard deviation for weight initialization +## We used 0.014 for 350M/1.3B dense/MoE models, and used 0.01 for 6.7B +## dense model. Usually larger model needs lower std. +INIT_STD=0.014 +# INIT_STD=0.01 + +## Activation checkpointing saves GPU memory, but reduces training speed +ACTIVATION_CHECKPOINT="true" +# ACTIVATION_CHECKPOINT="false" +############################################################################### +### Output and data configs +current_time=$(date "+%Y.%m.%d-%H.%M.%S") +host="${HOSTNAME}" +NAME="gpt-${MODEL_SIZE}B-lr-${LR}-minlr-${MIN_LR}-bs-${GLOBAL_BATCH_SIZE}-gpus-${NUM_GPUS}-mp-${MP_SIZE}-pp-${PP_SIZE}" +NAME="${NAME}-ep-pyramid-32+64-mos-mlc-${MLC}-cap-${MOE_TRAIN_CAP_FACTOR}-drop-${MOE_DROP_TOKEN}" + +if [ "${CL_ENABLED}" = "true" ]; then + NAME="${NAME}-cl-${CL_START_SEQLEN}-${CL_STEP}" +fi + +OUTPUT_BASEPATH=$DIR/output +mkdir -p "${OUTPUT_BASEPATH}/tensorboard/" +mkdir -p "${OUTPUT_BASEPATH}/checkpoint/" +mkdir -p "${OUTPUT_BASEPATH}/log/" +TENSORBOARD_DIR="${OUTPUT_BASEPATH}/tensorboard/${NAME}_${host}_${current_time}" +mkdir -p ${TENSORBOARD_DIR} +## Note that for MoE model with billion-scale base model, the checkpoint can be +## as large as TB-scale which normal NFS cannot handle efficiently. +CHECKPOINT_PATH="${OUTPUT_BASEPATH}/checkpoint/${NAME}" + +### Mixture-of-Students (MoS) configs +KD_BETA_CE=1 +CHECKPOINT_PATH_STUDENT="${OUTPUT_BASEPATH}/checkpoint/${NAME}" +CHECKPOINT_PATH_TEACHER="${OUTPUT_BASEPATH}/checkpoint/gpt-1.3B-lr-1.2e-4-minlr-1.0e-6-bs-512-gpus-128-mp-1-pp-1-ep-pyramid-64+128-mlc-0.01-cap-1.0-drop-true/" +CHECKPOINT_PATH_SAVE="${OUTPUT_BASEPATH}/checkpoint/${NAME}" + +USE_INTERNAL_DATA="true" +# USE_INTERNAL_DATA="false" + +if [ "${USE_INTERNAL_DATA}" = "true" ]; then + ## The internal data is only accessible within Microsoft + ## For cluster Azure-EastUS-V100-32GB-4, Azure-WestUS3-A100 + BASE_DATA_PATH=/vc_data/Megatron-LM/data + DATA_HOME="/vc_data/pile-cc1-cc2-shuf" + ## For cluster Lab-RR1-V100 + # BASE_DATA_PATH=/data/Megatron-LM/data + # DATA_HOME="/turing-ssd/users/conglli/data/pile-cc1-cc2-shuf" + ## For cluster Azure-CentralUS-A100 + # BASE_DATA_PATH=/data/Megatron-LM/data + # DATA_HOME=/vc_data_1/users/amawa/blended + + VOCAB_PATH=${BASE_DATA_PATH}/gpt2-vocab.json + MERGE_PATH=${BASE_DATA_PATH}/gpt2-merges.txt + ARX="${DATA_HOME}/ArXiv_ftfy_cleaned_id_shuf_text_document" + BC2="${DATA_HOME}/BookCorpus2_ftfy_cleaned_id_shuf_text_document" + B3="${DATA_HOME}/Books3_ftfy_cleaned_id_shuf_text_document" + CC2020="${DATA_HOME}/CC-2020-50_id_cleaned_shuf_text_document" + CC2021="${DATA_HOME}/CC-2021-04_id_cleaned_shuf_text_document" + GIT="${DATA_HOME}/Github_ftfy_id_shuf_text_document" + GUT="${DATA_HOME}/Gutenberg_PG-19_ftfy_cleaned_id_cleaned_shuf_text_document" + NIH="${DATA_HOME}/NIH_ExPorter_ftfy_id_shuf_text_document" + OWT2="${DATA_HOME}/OpenWebText2_ftfy_cleaned_id_shuf_text_document" + PCC="${DATA_HOME}/Pile-CC_id_cleaned_shuf_text_document" + PM="${DATA_HOME}/PubMed_Abstracts_ftfy_id_shuf_text_document" + RN="${DATA_HOME}/rn_dedup_shuf_cleaned_0.7_cleaned_shuf_text_document" + SE="${DATA_HOME}/StackExchange_ftfy_id_shuf_text_document" + ST="${DATA_HOME}/stories_dedup0.7_shuf_cleaned_shuf_text_document" + WIK="${DATA_HOME}/Wikipedia_en_ftfy_id_shuf_text_document" + DATA_BLEND="0.14336 ${B3} 0.08962 ${RN} 0.19336 ${OWT2} 0.05689 ${SE} \ + 0.00859 ${ST} 0.02897 ${PM} 0.04771 ${WIK} 0.00873 ${GUT} 0.01007 ${BC2} \ + 0.00208 ${NIH} 0.13017 ${CC2020} 0.09446 ${PCC} 0.15652 ${CC2021} \ + 0.01359 ${ARX} 0.01588 ${GIT}" +else + ## Placeholder, we plan to test a public dataset + VOCAB_PATH="" + MERGE_PATH="" + DATA_BLEND="" +fi +############################################################################### +data_options=" \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --data-path ${DATA_BLEND} \ + --data-impl mmap" + +megatron_options=" \ + --override-lr-scheduler \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --tensor-model-parallel-size ${MP_SIZE} \ + --moe-expert-parallel-size ${EP_PARALLEL_SIZE} \ + --num-experts ${EP_SIZE} \ + --moe-loss-coeff ${MLC} \ + --mlp-type residual \ + --moe-train-capacity-factor ${MOE_TRAIN_CAP_FACTOR} \ + --moe-eval-capacity-factor ${MOE_EVAL_CAP_FACTOR} \ + --moe-min-capacity ${MOE_MIN_CAP} \ + --init-method-std ${INIT_STD} \ + --lr-decay-tokens ${LR_DECAY_TOKENS} \ + --lr-warmup-tokens ${WARMUP_TOKENS} \ + --micro-batch-size ${BATCH_SIZE} \ + --exit-duration-in-mins ${EXIT_DURATION} \ + --global-batch-size ${GLOBAL_BATCH_SIZE} \ + --num-layers 21 \ + --hidden-size ${HIDDEN_SIZE} \ + --num-attention-heads ${NUM_ATTN_HEADS} \ + --seq-length ${SEQ_LEN} \ + --max-position-embeddings ${SEQ_LEN} \ + --train-tokens ${TRAIN_TOKENS} \ + --train-iters ${TRAIN_ITERS} \ + --lr ${LR} \ + --min-lr ${MIN_LR} \ + --lr-decay-style cosine \ + --split 98,2,0 \ + --log-interval ${LOG_INTERVAL} \ + --eval-interval ${EVAL_INTERVAL} \ + --eval-iters ${EVAL_ITERS} \ + --save-interval ${SAVE_INTERVAL} \ + --weight-decay 0.1 \ + --clip-grad 1.0 \ + --hysteresis 2 \ + --num-workers 0 \ + --fp16 \ + --load ${CHECKPOINT_PATH_STUDENT} \ + --save ${CHECKPOINT_PATH_SAVE} \ + --mos \ + --kd-beta-ce ${KD_BETA_CE} \ + --num-layers-teacher ${NUM_LAYERS} \ + --num-experts-teacher ${EP_SIZE_TEACHER} \ + --hidden-size-teacher ${HIDDEN_SIZE} \ + --num-attention-heads-teacher ${NUM_ATTN_HEADS} \ + --load-teacher ${CHECKPOINT_PATH_TEACHER} \ + --tensorboard-queue-size 1 \ + --log-timers-to-tensorboard \ + --log-batch-size-to-tensorboard \ + --log-validation-ppl-to-tensorboard \ + --tensorboard-dir ${TENSORBOARD_DIR}" + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +megatron_options="${megatron_options} \ + --checkpoint-activations" +fi + +megatron_options="${megatron_options} \ + --create-moe-param-group" + +if [ "${MOE_DROP_TOKEN}" = "false" ]; then +megatron_options="${megatron_options} \ + --disable-moe-token-dropping" +fi + +template_json="ds_config_gpt_TEMPLATE.json" +config_json="ds_config_gpt_${NAME}.json" +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} + +deepspeed_options=" \ + --deepspeed \ + --deepspeed_config ${config_json} \ + --pipeline-model-parallel-size ${PP_SIZE}" + +# Currently MoE is not compatible with pipeline parallel +deepspeed_options="${deepspeed_options} \ + --no-pipeline-parallel" + + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +deepspeed_options="${deepspeed_options} \ + --deepspeed-activation-checkpointing" +fi + +run_cmd="deepspeed ${DIR}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &> ${OUTPUT_BASEPATH}/log/${NAME}_${host}_${current_time}.log" +echo ${run_cmd} +eval ${run_cmd} +set +x diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_350M_dense.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_350M_dense.sh new file mode 100644 index 0000000000000000000000000000000000000000..79560ec4ff9897643bb49ef5cdea3e20cca366e1 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_350M_dense.sh @@ -0,0 +1,349 @@ +#!/bin/bash +DIR=`pwd` +############################################################################### +### Main configs +## GPT-3 models use 2K sequence length/context window +SEQ_LEN=2048 + +### The "GPT-3 XXX" below are configs from GPT-3 paper +### https://arxiv.org/abs/2005.14165, choose based on +### your desired model size or build your own configs + +## GPT-3 Small 125M +# MODEL_SIZE=0.125 +# NUM_LAYERS=12 +# HIDDEN_SIZE=768 +# NUM_ATTN_HEADS=12 +# GLOBAL_BATCH_SIZE=256 +# LR=6.0e-4 +# MIN_LR=6.0e-5 + +## GPT-3 Medium 350M +MODEL_SIZE=0.35 +NUM_LAYERS=24 +HIDDEN_SIZE=1024 +NUM_ATTN_HEADS=16 +GLOBAL_BATCH_SIZE=256 +LR=3.0e-4 +MIN_LR=3.0e-5 + +## GPT-3 Large 760M +# MODEL_SIZE=0.76 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1536 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=2.5e-4 +# MIN_LR=2.5e-5 + +## GPT-3 XL 1.3B +# MODEL_SIZE=1.3 +# NUM_LAYERS=24 +# HIDDEN_SIZE=2048 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=512 +# LR=2.0e-4 +# MIN_LR=2.0e-5 + +## GPT-3 2.7B +# MODEL_SIZE=2.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=2560 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=512 +# LR=1.6e-4 +# MIN_LR=1.6e-5 + +## GPT-3 6.7B +# MODEL_SIZE=6.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=4096 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.2e-4 +# MIN_LR=1.2e-5 + +## GPT-3 13B +# MODEL_SIZE=13 +# NUM_LAYERS=40 +# HIDDEN_SIZE=5120 +# NUM_ATTN_HEADS=40 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.0e-4 +# MIN_LR=1.0e-5 + +## GPT-3 175B +# MODEL_SIZE=175 +# NUM_LAYERS=96 +# HIDDEN_SIZE=12288 +# NUM_ATTN_HEADS=96 +# GLOBAL_BATCH_SIZE=1536 +# LR=0.6e-4 +# MIN_LR=0.6e-5 +############################################################################### +### Training duration configs +## The main termination condition, original GPT-3 paper trains for 300B tokens +## For MoE model, we found sometimes training a bit more to 330B tokens helps +TRAIN_TOKENS=300000000000 +# TRAIN_TOKENS=330000000000 + +## TRAIN_SAMPLES is another termination condition and also affect the number of +## data samples to be indexed. Since we want to reach the TRAIN_TOKENS +## above, and techniques like curriculum learning has less token in some steps, +## so we just set this config large enough to make sure we have enough +## processed data and don't terminate by TRAIN_SAMPLES. +TRAIN_SAMPLES=$(( ${TRAIN_TOKENS} * 3 / ${SEQ_LEN} )) + +## Another termination condition in minutes. Set it large enough to avoid +## undesired early termination. +EXIT_DURATION=30000000 +############################################################################### +### LR configs +## LR warmup and decay duration, this token-based config is preferable since +## no need to readjust when the batch size/seqlen is changed. +## Original GPT-3 paper uses 375M warmup tokens and 260B decay tokens. +## For MoE model, we found that setting the decay token to 300B helps. +WARMUP_TOKENS=375000000 +LR_DECAY_TOKENS=260000000000 +# LR_DECAY_TOKENS=300000000000 +############################################################################### +### Parallelism configs +## Micro batch size per GPU +## Make sure that BATCH_SIZE <= GLOBAL_BATCH_SIZE*PP_SIZE*MP_SIZE/NUM_GPUS +BATCH_SIZE=4 + +## Model parallelism, 1 is no MP +## Currently MoE models have divergence issue when MP > 1. +MP_SIZE=1 + +## Pipeline parallelism +## Currently we don't support PP for MoE. To disable PP, set PP_SIZE +## to 1 and use the "--no-pipeline-parallel" arg. +PP_SIZE=1 +NUM_GPUS=64 +############################################################################### +### MoE configs +## Number of experts. EP_SIZE 1 means dense model without MoE +EP_SIZE=1 +# EP_SIZE=128 + +if [[ $EP_SIZE -gt $NUM_GPUS ]]; then + EP_PARALLEL_SIZE=$NUM_GPUS +else + EP_PARALLEL_SIZE=$EP_SIZE +fi + +## Original GPT-3 model always set min LR at 10% of max LR. For MoE model, we +## found that lower LR and min LR (than the base dense model) helps. +## For 1.3B MoE-128 model we used LR=1.2e-4 and MIN_LR=1.0e-6. +## For 350M MoE-128 model we used LR=2.0e-4 and MIN_LR=2.0e-6, but they are not +## heavily tuned. +# LR=2.0e-4 +# MIN_LR=2e-06 + +## Coefficient for MoE loss. We find that 0.01 is a good value at least for +## 1.3B MoE-128 model +MLC=0.01 + +## Below configs adjust the MoE expert token capacity limit during training and +## eval. To completely disable capacity limit, set MOE_DROP_TOKEN to false. +## Larger capacity factor or disabling capacity limit could improve training +## convergence, but will also reduce training throughput. +MOE_TRAIN_CAP_FACTOR=1.0 +MOE_EVAL_CAP_FACTOR=1.0 +MOE_MIN_CAP=4 +MOE_DROP_TOKEN="true" +# MOE_DROP_TOKEN="false" +############################################################################### +### Curriculum learning (CL) configs +## Enable/disable CL +CL_ENABLED="false" +## Consult the tutorial https://www.deepspeed.ai/tutorials/curriculum-learning/ +## for tuning the following configs +CL_START_SEQLEN=80 +CL_AVG_SEQLEN=$(( (${CL_START_SEQLEN} + ${SEQ_LEN}) / 2 )) +CL_TOKENS=60 +CL_TOKENS=$((${CL_TOKENS} * 1000000000)) +CL_STEP=$(( ${CL_TOKENS} / (${GLOBAL_BATCH_SIZE} * ${CL_AVG_SEQLEN}) )) +############################################################################### +### Misc configs +LOG_INTERVAL=10 +EVAL_ITERS=10 +EVAL_INTERVAL=100 +SAVE_INTERVAL=1000 + +## Standard deviation for weight initialization +## We used 0.014 for 350M/1.3B dense/MoE models, and used 0.01 for 6.7B +## dense model. Usually larger model needs lower std. +INIT_STD=0.014 +# INIT_STD=0.01 + +## Activation checkpointing saves GPU memory, but reduces training speed +ACTIVATION_CHECKPOINT="true" +# ACTIVATION_CHECKPOINT="false" +############################################################################### +### Output and data configs +current_time=$(date "+%Y.%m.%d-%H.%M.%S") +host="${HOSTNAME}" +NAME="gpt-${MODEL_SIZE}B-lr-${LR}-minlr-${MIN_LR}-bs-${GLOBAL_BATCH_SIZE}-gpus-${NUM_GPUS}-mp-${MP_SIZE}-pp-${PP_SIZE}" +if [[ $EP_SIZE -gt 1 ]]; then + NAME="${NAME}-ep-${EP_SIZE}-mlc-${MLC}-cap-${MOE_TRAIN_CAP_FACTOR}-drop-${MOE_DROP_TOKEN}" +fi +if [ "${CL_ENABLED}" = "true" ]; then + NAME="${NAME}-cl-${CL_START_SEQLEN}-${CL_STEP}" +fi + +OUTPUT_BASEPATH=$DIR/output +mkdir -p "${OUTPUT_BASEPATH}/tensorboard/" +mkdir -p "${OUTPUT_BASEPATH}/checkpoint/" +mkdir -p "${OUTPUT_BASEPATH}/log/" +TENSORBOARD_DIR="${OUTPUT_BASEPATH}/tensorboard/${NAME}_${host}_${current_time}" +mkdir -p ${TENSORBOARD_DIR} +## Note that for MoE model with billion-scale base model, the checkpoint can be +## as large as TB-scale which normal NFS cannot handle efficiently. +CHECKPOINT_PATH="${OUTPUT_BASEPATH}/checkpoint/${NAME}" + +# USE_INTERNAL_DATA="true" +USE_INTERNAL_DATA="false" + +if [ "${USE_INTERNAL_DATA}" = "true" ]; then + ## The internal data is only accessible within Microsoft + ## For cluster Azure-EastUS-V100-32GB-4, Azure-WestUS3-A100 + # BASE_DATA_PATH=/vc_data/Megatron-LM/data + # DATA_HOME="/vc_data/pile-cc1-cc2-shuf" + ## For cluster Lab-RR1-V100 + BASE_DATA_PATH=/data/Megatron-LM/data + DATA_HOME="/turing-ssd/users/conglli/data/pile-cc1-cc2-shuf" + ## For cluster Azure-CentralUS-A100 + # BASE_DATA_PATH=/data/Megatron-LM/data + # DATA_HOME=/vc_data_1/users/amawa/blended + + VOCAB_PATH=${BASE_DATA_PATH}/gpt2-vocab.json + MERGE_PATH=${BASE_DATA_PATH}/gpt2-merges.txt + ARX="${DATA_HOME}/ArXiv_ftfy_cleaned_id_shuf_text_document" + BC2="${DATA_HOME}/BookCorpus2_ftfy_cleaned_id_shuf_text_document" + B3="${DATA_HOME}/Books3_ftfy_cleaned_id_shuf_text_document" + CC2020="${DATA_HOME}/CC-2020-50_id_cleaned_shuf_text_document" + CC2021="${DATA_HOME}/CC-2021-04_id_cleaned_shuf_text_document" + GIT="${DATA_HOME}/Github_ftfy_id_shuf_text_document" + GUT="${DATA_HOME}/Gutenberg_PG-19_ftfy_cleaned_id_cleaned_shuf_text_document" + NIH="${DATA_HOME}/NIH_ExPorter_ftfy_id_shuf_text_document" + OWT2="${DATA_HOME}/OpenWebText2_ftfy_cleaned_id_shuf_text_document" + PCC="${DATA_HOME}/Pile-CC_id_cleaned_shuf_text_document" + PM="${DATA_HOME}/PubMed_Abstracts_ftfy_id_shuf_text_document" + RN="${DATA_HOME}/rn_dedup_shuf_cleaned_0.7_cleaned_shuf_text_document" + SE="${DATA_HOME}/StackExchange_ftfy_id_shuf_text_document" + ST="${DATA_HOME}/stories_dedup0.7_shuf_cleaned_shuf_text_document" + WIK="${DATA_HOME}/Wikipedia_en_ftfy_id_shuf_text_document" + DATA_BLEND="0.14336 ${B3} 0.08962 ${RN} 0.19336 ${OWT2} 0.05689 ${SE} \ + 0.00859 ${ST} 0.02897 ${PM} 0.04771 ${WIK} 0.00873 ${GUT} 0.01007 ${BC2} \ + 0.00208 ${NIH} 0.13017 ${CC2020} 0.09446 ${PCC} 0.15652 ${CC2021} \ + 0.01359 ${ARX} 0.01588 ${GIT}" +else + VOCAB_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-vocab.json + MERGE_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-merges.txt + # Public the Pile dataset, can be downloaded at https://mystic.the-eye.eu/public/AI/pile_neox/ + DATA_BLEND=/data/the_pile_public_merged_nopreprocessing/pile_text_document +fi +############################################################################### +data_options=" \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --data-path ${DATA_BLEND} \ + --data-impl mmap" + +megatron_options=" \ + --override-lr-scheduler \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --tensor-model-parallel-size ${MP_SIZE} \ + --moe-expert-parallel-size ${EP_PARALLEL_SIZE} \ + --num-experts ${EP_SIZE} \ + --moe-loss-coeff ${MLC} \ + --moe-train-capacity-factor ${MOE_TRAIN_CAP_FACTOR} \ + --moe-eval-capacity-factor ${MOE_EVAL_CAP_FACTOR} \ + --moe-min-capacity ${MOE_MIN_CAP} \ + --init-method-std ${INIT_STD} \ + --lr-decay-tokens ${LR_DECAY_TOKENS} \ + --lr-warmup-tokens ${WARMUP_TOKENS} \ + --micro-batch-size ${BATCH_SIZE} \ + --exit-duration-in-mins ${EXIT_DURATION} \ + --global-batch-size ${GLOBAL_BATCH_SIZE} \ + --num-layers ${NUM_LAYERS} \ + --hidden-size ${HIDDEN_SIZE} \ + --num-attention-heads ${NUM_ATTN_HEADS} \ + --seq-length ${SEQ_LEN} \ + --max-position-embeddings ${SEQ_LEN} \ + --train-tokens ${TRAIN_TOKENS} \ + --train-samples ${TRAIN_SAMPLES} \ + --lr ${LR} \ + --min-lr ${MIN_LR} \ + --lr-decay-style cosine \ + --split 98,2,0 \ + --log-interval ${LOG_INTERVAL} \ + --eval-interval ${EVAL_INTERVAL} \ + --eval-iters ${EVAL_ITERS} \ + --save-interval ${SAVE_INTERVAL} \ + --weight-decay 0.1 \ + --clip-grad 1.0 \ + --hysteresis 2 \ + --num-workers 0 \ + --fp16 \ + --load ${CHECKPOINT_PATH} \ + --save ${CHECKPOINT_PATH} \ + --tensorboard-queue-size 1 \ + --log-timers-to-tensorboard \ + --log-batch-size-to-tensorboard \ + --log-validation-ppl-to-tensorboard \ + --tensorboard-dir ${TENSORBOARD_DIR}" + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +megatron_options="${megatron_options} \ + --checkpoint-activations" +fi + +if [[ $EP_SIZE -gt 1 ]]; then +megatron_options="${megatron_options} \ + --create-moe-param-group" +fi + +if [ "${MOE_DROP_TOKEN}" = "false" ]; then +megatron_options="${megatron_options} \ + --disable-moe-token-dropping" +fi + +template_json="ds_config_gpt_TEMPLATE.json" +config_json="ds_config_gpt_${NAME}.json" +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/ZERO_STAGE/0/" \ + | sed "s/PRESCALE_GRAD/true/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} + +deepspeed_options=" \ + --deepspeed \ + --deepspeed_config ${config_json} \ + --pipeline-model-parallel-size ${PP_SIZE}" + +# Currently MoE is not compatible with pipeline parallel +if [[ $EP_SIZE -gt 1 ]]; then +deepspeed_options="${deepspeed_options} \ + --no-pipeline-parallel" +fi + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +deepspeed_options="${deepspeed_options} \ + --deepspeed-activation-checkpointing" +fi + +run_cmd="deepspeed ${DIR}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &> ${OUTPUT_BASEPATH}/log/${NAME}_${host}_${current_time}.log" +echo ${run_cmd} +eval ${run_cmd} +set +x diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_6.7B_dense.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_6.7B_dense.sh new file mode 100644 index 0000000000000000000000000000000000000000..6349354b1c87aba96d70c60ed5c82c2682835f90 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/ds_pretrain_gpt_6.7B_dense.sh @@ -0,0 +1,350 @@ +#!/bin/bash +DIR=`pwd` +############################################################################### +### Main configs +## GPT-3 models use 2K sequence length/context window +SEQ_LEN=2048 + +### The "GPT-3 XXX" below are configs from GPT-3 paper +### https://arxiv.org/abs/2005.14165, choose based on +### your desired model size or build your own configs + +## GPT-3 Small 125M +# MODEL_SIZE=0.125 +# NUM_LAYERS=12 +# HIDDEN_SIZE=768 +# NUM_ATTN_HEADS=12 +# GLOBAL_BATCH_SIZE=256 +# LR=6.0e-4 +# MIN_LR=6.0e-5 + +## GPT-3 Medium 350M +# MODEL_SIZE=0.35 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1024 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=3.0e-4 +# MIN_LR=3.0e-5 + +## GPT-3 Large 760M +# MODEL_SIZE=0.76 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1536 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=2.5e-4 +# MIN_LR=2.5e-5 + +## GPT-3 XL 1.3B +# MODEL_SIZE=1.3 +# NUM_LAYERS=24 +# HIDDEN_SIZE=2048 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=512 +# LR=2.0e-4 +# MIN_LR=2.0e-5 + +## GPT-3 2.7B +# MODEL_SIZE=2.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=2560 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=512 +# LR=1.6e-4 +# MIN_LR=1.6e-5 + +## GPT-3 6.7B +MODEL_SIZE=6.7 +NUM_LAYERS=32 +HIDDEN_SIZE=4096 +NUM_ATTN_HEADS=32 +GLOBAL_BATCH_SIZE=1024 +LR=1.2e-4 +MIN_LR=1.2e-5 + +## GPT-3 13B +# MODEL_SIZE=13 +# NUM_LAYERS=40 +# HIDDEN_SIZE=5120 +# NUM_ATTN_HEADS=40 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.0e-4 +# MIN_LR=1.0e-5 + +## GPT-3 175B +# MODEL_SIZE=175 +# NUM_LAYERS=96 +# HIDDEN_SIZE=12288 +# NUM_ATTN_HEADS=96 +# GLOBAL_BATCH_SIZE=1536 +# LR=0.6e-4 +# MIN_LR=0.6e-5 +############################################################################### +### Training duration configs +## The main termination condition, original GPT-3 paper trains for 300B tokens +## For MoE model, we found sometimes training a bit more to 330B tokens helps +TRAIN_TOKENS=300000000000 +# TRAIN_TOKENS=330000000000 + +## TRAIN_SAMPLES is another termination condition and also affect the number of +## data samples to be indexed. Since we want to reach the TRAIN_TOKENS +## above, and techniques like curriculum learning has less token in some steps, +## so we just set this config large enough to make sure we have enough +## processed data and don't terminate by TRAIN_SAMPLES. +TRAIN_SAMPLES=$(( ${TRAIN_TOKENS} * 3 / ${SEQ_LEN} )) + +## Another termination condition in minutes. Set it large enough to avoid +## undesired early termination. +EXIT_DURATION=30000000 +############################################################################### +### LR configs +## LR warmup and decay duration, this token-based config is preferable since +## no need to readjust when the batch size/seqlen is changed. +## Original GPT-3 paper uses 375M warmup tokens and 260B decay tokens. +## For MoE model, we found that setting the decay token to 300B helps. +WARMUP_TOKENS=375000000 +LR_DECAY_TOKENS=260000000000 +# LR_DECAY_TOKENS=300000000000 +############################################################################### +### Parallelism configs +## Micro batch size per GPU +## Make sure that BATCH_SIZE <= GLOBAL_BATCH_SIZE*PP_SIZE*MP_SIZE/NUM_GPUS +BATCH_SIZE=4 + +## Model parallelism, 1 is no MP +## Currently MoE models have divergence issue when MP > 1. +MP_SIZE=8 + +## Pipeline parallelism +## Currently we don't support PP for MoE. To disable PP, set PP_SIZE +## to 1 and use the "--no-pipeline-parallel" arg. +PP_SIZE=1 +NUM_GPUS=64 +############################################################################### +### MoE configs +## Number of experts. EP_SIZE 1 means dense model without MoE +EP_SIZE=1 +# EP_SIZE=128 + +if [[ $EP_SIZE -gt $NUM_GPUS ]]; then + EP_PARALLEL_SIZE=$NUM_GPUS +else + EP_PARALLEL_SIZE=$EP_SIZE +fi + +## Original GPT-3 model always set min LR at 10% of max LR. For MoE model, we +## found that lower LR and min LR (than the base dense model) helps. +## For 1.3B MoE-128 model we used LR=1.2e-4 and MIN_LR=1.0e-6. +## For 350M MoE-128 model we used LR=2.0e-4 and MIN_LR=2.0e-6, but they are not +## heavily tuned. +# LR=2.0e-4 +# MIN_LR=2e-06 + +## Coefficient for MoE loss. We find that 0.01 is a good value at least for +## 1.3B MoE-128 model +MLC=0.01 + +## Below configs adjust the MoE expert token capacity limit during training and +## eval. To completely disable capacity limit, set MOE_DROP_TOKEN to false. +## Larger capacity factor or disabling capacity limit could improve training +## convergence, but will also reduce training throughput. +MOE_TRAIN_CAP_FACTOR=1.0 +MOE_EVAL_CAP_FACTOR=1.0 +MOE_MIN_CAP=4 +MOE_DROP_TOKEN="true" +# MOE_DROP_TOKEN="false" +############################################################################### +### Curriculum learning (CL) configs +## Enable/disable CL +CL_ENABLED="false" +## Consult the tutorial https://www.deepspeed.ai/tutorials/curriculum-learning/ +## for tuning the following configs +CL_START_SEQLEN=80 +CL_AVG_SEQLEN=$(( (${CL_START_SEQLEN} + ${SEQ_LEN}) / 2 )) +CL_TOKENS=60 +CL_TOKENS=$((${CL_TOKENS} * 1000000000)) +CL_STEP=$(( ${CL_TOKENS} / (${GLOBAL_BATCH_SIZE} * ${CL_AVG_SEQLEN}) )) +############################################################################### +### Misc configs +LOG_INTERVAL=10 +EVAL_ITERS=10 +EVAL_INTERVAL=100 +SAVE_INTERVAL=1000 + +## Standard deviation for weight initialization +## We used 0.014 for 350M/1.3B dense/MoE models, and used 0.01 for 6.7B +## dense model. Usually larger model needs lower std. +# INIT_STD=0.014 +INIT_STD=0.01 + +## Activation checkpointing saves GPU memory, but reduces training speed +ACTIVATION_CHECKPOINT="true" +# ACTIVATION_CHECKPOINT="false" +############################################################################### +### Output and data configs +current_time=$(date "+%Y.%m.%d-%H.%M.%S") +host="${HOSTNAME}" +NAME="gpt-${MODEL_SIZE}B-lr-${LR}-minlr-${MIN_LR}-bs-${GLOBAL_BATCH_SIZE}-gpus-${NUM_GPUS}-mp-${MP_SIZE}-pp-${PP_SIZE}" +if [[ $EP_SIZE -gt 1 ]]; then + NAME="${NAME}-ep-${EP_SIZE}-mlc-${MLC}-cap-${MOE_TRAIN_CAP_FACTOR}-drop-${MOE_DROP_TOKEN}" +fi +if [ "${CL_ENABLED}" = "true" ]; then + NAME="${NAME}-cl-${CL_START_SEQLEN}-${CL_STEP}" +fi + +OUTPUT_BASEPATH=$DIR/output +mkdir -p "${OUTPUT_BASEPATH}/tensorboard/" +mkdir -p "${OUTPUT_BASEPATH}/checkpoint/" +mkdir -p "${OUTPUT_BASEPATH}/log/" +TENSORBOARD_DIR="${OUTPUT_BASEPATH}/tensorboard/${NAME}_${host}_${current_time}" +mkdir -p ${TENSORBOARD_DIR} +## Note that for MoE model with billion-scale base model, the checkpoint can be +## as large as TB-scale which normal NFS cannot handle efficiently. +CHECKPOINT_PATH="${OUTPUT_BASEPATH}/checkpoint/${NAME}" + +# USE_INTERNAL_DATA="true" +USE_INTERNAL_DATA="false" + +if [ "${USE_INTERNAL_DATA}" = "true" ]; then + ## The internal data is only accessible within Microsoft + ## For cluster Azure-EastUS-V100-32GB-4, Azure-WestUS3-A100 + # BASE_DATA_PATH=/vc_data/Megatron-LM/data + # DATA_HOME="/vc_data/pile-cc1-cc2-shuf" + ## For cluster Lab-RR1-V100 + BASE_DATA_PATH=/data/Megatron-LM/data + DATA_HOME="/turing-ssd/users/conglli/data/pile-cc1-cc2-shuf" + ## For cluster Azure-CentralUS-A100 + # BASE_DATA_PATH=/data/Megatron-LM/data + # DATA_HOME=/vc_data_1/users/amawa/blended + + VOCAB_PATH=${BASE_DATA_PATH}/gpt2-vocab.json + MERGE_PATH=${BASE_DATA_PATH}/gpt2-merges.txt + ARX="${DATA_HOME}/ArXiv_ftfy_cleaned_id_shuf_text_document" + BC2="${DATA_HOME}/BookCorpus2_ftfy_cleaned_id_shuf_text_document" + B3="${DATA_HOME}/Books3_ftfy_cleaned_id_shuf_text_document" + CC2020="${DATA_HOME}/CC-2020-50_id_cleaned_shuf_text_document" + CC2021="${DATA_HOME}/CC-2021-04_id_cleaned_shuf_text_document" + GIT="${DATA_HOME}/Github_ftfy_id_shuf_text_document" + GUT="${DATA_HOME}/Gutenberg_PG-19_ftfy_cleaned_id_cleaned_shuf_text_document" + NIH="${DATA_HOME}/NIH_ExPorter_ftfy_id_shuf_text_document" + OWT2="${DATA_HOME}/OpenWebText2_ftfy_cleaned_id_shuf_text_document" + PCC="${DATA_HOME}/Pile-CC_id_cleaned_shuf_text_document" + PM="${DATA_HOME}/PubMed_Abstracts_ftfy_id_shuf_text_document" + RN="${DATA_HOME}/rn_dedup_shuf_cleaned_0.7_cleaned_shuf_text_document" + SE="${DATA_HOME}/StackExchange_ftfy_id_shuf_text_document" + ST="${DATA_HOME}/stories_dedup0.7_shuf_cleaned_shuf_text_document" + WIK="${DATA_HOME}/Wikipedia_en_ftfy_id_shuf_text_document" + DATA_BLEND="0.14336 ${B3} 0.08962 ${RN} 0.19336 ${OWT2} 0.05689 ${SE} \ + 0.00859 ${ST} 0.02897 ${PM} 0.04771 ${WIK} 0.00873 ${GUT} 0.01007 ${BC2} \ + 0.00208 ${NIH} 0.13017 ${CC2020} 0.09446 ${PCC} 0.15652 ${CC2021} \ + 0.01359 ${ARX} 0.01588 ${GIT}" +else + VOCAB_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-vocab.json + MERGE_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-merges.txt + # Public the Pile dataset, can be downloaded at https://mystic.the-eye.eu/public/AI/pile_neox/ + DATA_BLEND=/data/the_pile_public_merged_nopreprocessing/pile_text_document +fi +############################################################################### +data_options=" \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --data-path ${DATA_BLEND} \ + --data-impl mmap" + +megatron_options=" \ + --override-lr-scheduler \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --tensor-model-parallel-size ${MP_SIZE} \ + --moe-expert-parallel-size ${EP_PARALLEL_SIZE} \ + --num-experts ${EP_SIZE} \ + --moe-loss-coeff ${MLC} \ + --moe-train-capacity-factor ${MOE_TRAIN_CAP_FACTOR} \ + --moe-eval-capacity-factor ${MOE_EVAL_CAP_FACTOR} \ + --moe-min-capacity ${MOE_MIN_CAP} \ + --init-method-std ${INIT_STD} \ + --lr-decay-tokens ${LR_DECAY_TOKENS} \ + --lr-warmup-tokens ${WARMUP_TOKENS} \ + --micro-batch-size ${BATCH_SIZE} \ + --exit-duration-in-mins ${EXIT_DURATION} \ + --rampup-batch-size 32 32 4882812 \ + --global-batch-size ${GLOBAL_BATCH_SIZE} \ + --num-layers ${NUM_LAYERS} \ + --hidden-size ${HIDDEN_SIZE} \ + --num-attention-heads ${NUM_ATTN_HEADS} \ + --seq-length ${SEQ_LEN} \ + --max-position-embeddings ${SEQ_LEN} \ + --train-tokens ${TRAIN_TOKENS} \ + --train-samples ${TRAIN_SAMPLES} \ + --lr ${LR} \ + --min-lr ${MIN_LR} \ + --lr-decay-style cosine \ + --split 98,2,0 \ + --log-interval ${LOG_INTERVAL} \ + --eval-interval ${EVAL_INTERVAL} \ + --eval-iters ${EVAL_ITERS} \ + --save-interval ${SAVE_INTERVAL} \ + --weight-decay 0.1 \ + --clip-grad 1.0 \ + --hysteresis 2 \ + --num-workers 0 \ + --fp16 \ + --load ${CHECKPOINT_PATH} \ + --save ${CHECKPOINT_PATH} \ + --tensorboard-queue-size 1 \ + --log-timers-to-tensorboard \ + --log-batch-size-to-tensorboard \ + --log-validation-ppl-to-tensorboard \ + --tensorboard-dir ${TENSORBOARD_DIR}" + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +megatron_options="${megatron_options} \ + --checkpoint-activations" +fi + +if [[ $EP_SIZE -gt 1 ]]; then +megatron_options="${megatron_options} \ + --create-moe-param-group" +fi + +if [ "${MOE_DROP_TOKEN}" = "false" ]; then +megatron_options="${megatron_options} \ + --disable-moe-token-dropping" +fi + +template_json="ds_config_gpt_TEMPLATE.json" +config_json="ds_config_gpt_${NAME}.json" +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/ZERO_STAGE/0/" \ + | sed "s/PRESCALE_GRAD/true/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} + +deepspeed_options=" \ + --deepspeed \ + --deepspeed_config ${config_json} \ + --pipeline-model-parallel-size ${PP_SIZE}" + +# Currently MoE is not compatible with pipeline parallel +if [[ $EP_SIZE -gt 1 ]]; then +deepspeed_options="${deepspeed_options} \ + --no-pipeline-parallel" +fi + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +deepspeed_options="${deepspeed_options} \ + --deepspeed-activation-checkpointing" +fi + +run_cmd="deepspeed ${DIR}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &> ${OUTPUT_BASEPATH}/log/${NAME}_${host}_${current_time}.log" +echo ${run_cmd} +eval ${run_cmd} +set +x diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/readme_evalharness.md b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/readme_evalharness.md new file mode 100644 index 0000000000000000000000000000000000000000..5a33c09478e4553260fb4bb02e453d3a4cf36c30 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/MoE/readme_evalharness.md @@ -0,0 +1,168 @@ +# How to run lm-eval on Megatron-DeepSpeed checkpoint using the original setup + +A great portion of this eval harness feature is inherited from https://github.com/bigscience-workshop/Megatron-DeepSpeed/pull/212, but with code/doc changes (e.g., to support case without pipeline parallelism and MoE models). + +This particular setup uses the normal deepspeed checkpoint and requires no conversion to Megatron-LM. + +## Prerequisites + +1. Install software + +On login console with external network + +Get lm-eval harness (https://github.com/EleutherAI/lm-evaluation-harness) and `best-download==0.0.7` needed to download some tasks. +``` +(maybe need pip install --upgrade pip) +pip install best-download==0.0.7 +pip install lm-eval +(previously we used "pip install git+https://github.com/EleutherAI/lm-evaluation-harness" to install, but later found the command above has less dependency issues) +``` + +2. Pre-download needed datasets + +some symlinks due to lm-harness' issues with relative position of data +``` +mkdir data +cd ../../tasks/eval_harness/ +ln -s ../../examples/MoE/data/ data +cd ../../examples/MoE/ +``` + + +Then install datasets for the tasks: +``` +python ../../tasks/eval_harness/download.py --task_list hellaswag,lambada,triviaqa,webqs,winogrande,piqa,arc_challenge,arc_easy,openbookqa,race,boolq,cb,copa,rte,wic,wsc,multirc,record,anli_r1,anli_r2,anli_r3,wikitext,logiqa,mathqa,mc_taco,mrpc,prost,pubmedqa,qnli,qqp,sciq,sst,wnli +``` +and make sure that `export HF_DATASETS_OFFLINE=1` + + + +3. Prepare the script + + + +`ds_evalharness.sh` is the example script. + +1. Edit: + +``` +PP_SIZE=1 +TP_SIZE=1 +NO_PP="true" +EP_PARALLEL_SIZE=1 +NUM_NODE=1 +NUM_GPU_PER_NODE=1 +``` +to match the eval topology. + +Edit: +``` +CHECKPOINT_PATH= +CONFIG_PATH= +RESULT_PATH= +``` +to the checkpoint/ds config you want to use, and where to save the results. + + + +2. Adjust the following to fit the chosen GPU. As of last check for 1.3B model the settings are one of: +``` +EVAL_MICRO_BATCH_SIZE=6 # 16GB GPU 1.3B model +EVAL_MICRO_BATCH_SIZE=12 # 32GB GPU 1.3B model +``` + +If you get OOM lower it further. + +3. If not using the Deepspeed path, disable it by removing: + +``` + --deepspeed \ + --deepspeed_config ds_config.json \ +``` + +If you didn't disable it and the program crashed on checkpoint loading unable to find some key, disable deepspeed as explained above. + +Note that for MoE models and for models without pipeline parallelism, currently they might not work for the case without deepspeed. + + diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/azure/README.md b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/azure/README.md new file mode 100644 index 0000000000000000000000000000000000000000..81c83d6f85ba51e09d0a7a18e980c82c81a13c9e --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/azure/README.md @@ -0,0 +1,27 @@ +## Recipes for experimentation on Azure + +The recipes have been tested on command line on a cluster setup using Azure VMs and VMSS as well as inside Docker based environments. + +To run any of the examples in this folder, please go to the base directory of Megatron-DeepSpeed and run as follows + +```bash examples/azure/run-benchmark-model.sh``` + +### Pre-requisites + +To run the above script, you will need to either setup your own dataset and modify the scripts or use our helper scripts to download the publicly available Books dataset and GPT vocab files. Please use the following from the ```dataset``` folder + +```bash dataset/download_books.sh``` + +```bash dataset/download_vocab.sh``` + +### Run 175B and 1T models + +We have included two recipes for the 175B model and the 1T model. To train the model, we assume that the users will modify and tune hyperparameters and configurations by themselves. To facilitate initial training, we have made the recipes runnable with the Books dataset as follows. + +```bash examples/azure/run-175b.sh``` + +```bash examples/azure/run-1t.sh``` + +### Note about ZeRO stage 3 and CPU offload + +By default, we have enabled ZeRO Stage 3 for both the recipes above. For the 1T model, we have also enabled the CPU-offload feature to save on memory and enable a larger batch size that offers better performance. diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/azure/run-175b.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/azure/run-175b.sh new file mode 100644 index 0000000000000000000000000000000000000000..3e6b84a85111e34b3252dc77aa9d47250ffb27e5 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/azure/run-175b.sh @@ -0,0 +1,142 @@ +#!/bin/bash +set -ex + +data_options=" \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --data-path ${DATA_PATH} \ + --data-impl mmap" + +BASE_PATH=$PWD/dataset/ +DATA_PATH=${BASE_PATH}/BookCorpusDataset_text_document +DS_CONFIG=ds_config.json + +# Hostfile path +HF=/job/hostfile + +# Disabling tensor/pipeline parallelism +TP=1 +PP=1 + +# HEADS ~= HIDDEN/128 + +# Model: 175B +NLAYERS=96 +HIDDEN=12288 +HEADS=96 +SEQ=1024 + + +MICRO_BATCH=4 +NODES=1 +GPN=8 +GLOBAL_BATCH=$(( ${GPN} * ${MICRO_BATCH} * ${NODES} )) + +# Initial power scale for loss +SP=15 + +# Uncomment/comment one of the following blocks. + +# For 1T model, start with microbatch=1, try to get 2 and 4. If OOM w/ 4, use cpu-offloading + +# Set to cpu for offloading to cpu for larger models +#OFFLOAD_DEVICE="cpu" +#CPU_OPTIM=" --cpu-optimizer" + +# Set to none and empty string for no cpu offloading +OFFLOAD_DEVICE="none" +CPU_OPTIM=" " + +ZERO_STAGE=3 +OUTPUT_DIR=ds_z_off-${OFFLOAD_DEVICE}_stage_${ZERO_STAGE}_nl${NLAYERS}_hs${HIDDEN}_mb${MICRO_BATCH}_seq${SEQ}_gb${GLOBAL_BATCH}_nodes${NODES} +#OUTPUT_DIR=baseline_nl${NLAYERS}_hs${HIDDEN}_gb${GLOBAL_BATCH}_mb${MICRO_BATCH} +mkdir -p $OUTPUT_DIR + +cat < $DS_CONFIG +{ + "train_batch_size" : $GLOBAL_BATCH, + "train_micro_batch_size_per_gpu": $MICRO_BATCH, + "steps_per_print": 1, + "gradient_accumulation_steps": 1, + "zero_optimization": { + "stage": 3, + "stage3_max_live_parameters": 3e9, + "stage3_max_reuse_distance": 3e9, + "stage3_param_persistence_threshold": 1e5, + "stage3_prefetch_bucket_size": 5e7, + "contiguous_gradients": true, + "overlap_comm": true, + "reduce_bucket_size": 90000000, + "sub_group_size": 1e9, + "offload_optimizer": { + "device": "$OFFLOAD_DEVICE", + "buffer_count": 4, + "pipeline_read": false, + "pipeline_write": false, + "pin_memory": true + } + }, + "gradient_clipping": 1.0, + "fp16": { + "enabled": true, + "initial_scale_power" : $SP, + "loss_scale_window": 1000, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "wall_clock_breakdown": true, + "zero_allow_untested_optimizer": false, + "aio": { + "block_size": 1048576, + "queue_depth": 16, + "single_submit": false, + "overlap_events": true, + "thread_count": 2 + } +} +EOT + +export NCCL_DEBUG=warn + +ds_args=" " +ds_args=" --deepspeed ${ds_args}" +ds_args=" --no-pipeline-parallel ${ds_args}" +ds_args=" --deepspeed_config=$DS_CONFIG ${ds_args}" +ds_args=" --zero-stage=$ZERO_STAGE ${ds_args}" +ds_args=" --deepspeed-activation-checkpointing ${ds_args}" + + + +deepspeed --force_multi --num_nodes=$NODES --hostfile $HF pretrain_gpt.py \ + --tensor-model-parallel-size $TP \ + --pipeline-model-parallel-size $PP \ + --num-layers $NLAYERS \ + --hidden-size $HIDDEN \ + --num-attention-heads $HEADS \ + --seq-length $SEQ \ + --loss-scale $SP \ + --max-position-embeddings $SEQ \ + --micro-batch-size $MICRO_BATCH \ + --global-batch-size $GLOBAL_BATCH \ + --train-iters 1000 \ + --lr 6.0e-5 \ + --min-lr 6.0e-6 \ + --lr-decay-style cosine \ + --log-interval 1 \ + --eval-iters 40 \ + --eval-interval 1000 \ + --data-path $DATA_PATH \ + --vocab-file $BASE_PATH/gpt2-vocab.json \ + --merge-file $BASE_PATH/gpt2-merges.txt \ + --save-interval 1000 \ + --split 98,2,0 \ + --clip-grad 1.0 \ + --weight-decay 0.1 \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --init-method-std 0.006 \ + --fp16 \ + --checkpoint-activations \ + --tensorboard-dir $OUTPUT_DIR \ + $CPU_OPTIM $ds_args \ + --exit-interval 5000 | tee ${OUTPUT_DIR}/output.log diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/azure/run-1t.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/azure/run-1t.sh new file mode 100644 index 0000000000000000000000000000000000000000..6e93bcb06e8a4f8c982441e1dd8a5da652750a1a --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/azure/run-1t.sh @@ -0,0 +1,154 @@ +#!/bin/bash +set -ex + +data_options=" \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --data-path ${DATA_PATH} \ + --data-impl mmap" + +BASE_PATH=$PWD/dataset/ +DATA_PATH=${BASE_PATH}/BookCorpusDataset_text_document +DS_CONFIG=ds_config.json + +# Hostfile path +HF=/job/hostfile + +# Disabling tensor/pipeline parallelism +TP=1 +PP=1 + +# HEADS ~= HIDDEN/128 + +# Refer to Megatron-table in the README.md file for model sizes +# Model: 310B +#NLAYERS=96 +#HIDDEN=16384 +#HEADS=128 +#SEQ=2048 + +# Model 530B +#NLAYERS=105 +#HIDDEN=20480 +#HEADS=160 +#SEQ=2048 + +# Model 1T +NLAYERS=128 +HIDDEN=25600 +HEADS=160 +SEQ=1024 + +MICRO_BATCH=1 +NODES=1 +GPN=8 +GLOBAL_BATCH=$(( ${GPN} * ${MICRO_BATCH} * ${NODES} )) + +# Initial power scale for loss +SP=15 + +# Uncomment/comment one of the following blocks. + +# For 1T model, start with microbatch=1, try to get 2 and 4. If OOM w/ 4, use cpu-offloading + +# Set to cpu for offloading to cpu for larger models +OFFLOAD_DEVICE="cpu" +CPU_OPTIM=" --cpu-optimizer" + +# Set to none and empty string for no cpu offloading +#OFFLOAD_DEVICE="none" +#CPU_OPTIM=" " + +ZERO_STAGE=3 +OUTPUT_DIR=ds_z_off-${OFFLOAD_DEVICE}_stage_${ZERO_STAGE}_nl${NLAYERS}_hs${HIDDEN}_mb${MICRO_BATCH}_seq${SEQ}_gb${GLOBAL_BATCH}_nodes${NODES} +#OUTPUT_DIR=baseline_nl${NLAYERS}_hs${HIDDEN}_gb${GLOBAL_BATCH}_mb${MICRO_BATCH} +mkdir -p $OUTPUT_DIR + +cat < $DS_CONFIG +{ + "train_batch_size" : $GLOBAL_BATCH, + "train_micro_batch_size_per_gpu": $MICRO_BATCH, + "steps_per_print": 1, + "gradient_accumulation_steps": 1, + "zero_optimization": { + "stage": 3, + "stage3_max_live_parameters": 3e9, + "stage3_max_reuse_distance": 3e9, + "stage3_param_persistence_threshold": 1e5, + "stage3_prefetch_bucket_size": 5e7, + "contiguous_gradients": true, + "overlap_comm": true, + "reduce_bucket_size": 90000000, + "sub_group_size": 1e9, + "offload_optimizer": { + "device": "$OFFLOAD_DEVICE", + "buffer_count": 4, + "pipeline_read": false, + "pipeline_write": false, + "pin_memory": true + } + }, + "gradient_clipping": 1.0, + "fp16": { + "enabled": true, + "initial_scale_power" : $SP, + "loss_scale_window": 1000, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "wall_clock_breakdown": true, + "zero_allow_untested_optimizer": false, + "aio": { + "block_size": 1048576, + "queue_depth": 16, + "single_submit": false, + "overlap_events": true, + "thread_count": 2 + } +} +EOT + +export NCCL_DEBUG=warn + +ds_args=" " +ds_args=" --deepspeed ${ds_args}" +ds_args=" --no-pipeline-parallel ${ds_args}" +ds_args=" --deepspeed_config=$DS_CONFIG ${ds_args}" +ds_args=" --zero-stage=$ZERO_STAGE ${ds_args}" +ds_args=" --deepspeed-activation-checkpointing ${ds_args}" + + + +deepspeed --force_multi --num_nodes=$NODES --hostfile $HF pretrain_gpt.py \ + --tensor-model-parallel-size $TP \ + --pipeline-model-parallel-size $PP \ + --num-layers $NLAYERS \ + --hidden-size $HIDDEN \ + --num-attention-heads $HEADS \ + --seq-length $SEQ \ + --loss-scale $SP \ + --max-position-embeddings $SEQ \ + --micro-batch-size $MICRO_BATCH \ + --global-batch-size $GLOBAL_BATCH \ + --train-iters 1000 \ + --lr 6.0e-5 \ + --min-lr 6.0e-6 \ + --lr-decay-style cosine \ + --log-interval 1 \ + --eval-iters 40 \ + --eval-interval 1000 \ + --data-path $DATA_PATH \ + --vocab-file $BASE_PATH/gpt2-vocab.json \ + --merge-file $BASE_PATH/gpt2-merges.txt \ + --save-interval 1000 \ + --split 98,2,0 \ + --clip-grad 1.0 \ + --weight-decay 0.1 \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --init-method-std 0.006 \ + --fp16 \ + --checkpoint-activations \ + --tensorboard-dir $OUTPUT_DIR \ + $CPU_OPTIM $ds_args \ + --exit-interval 5000 | tee ${OUTPUT_DIR}/output.log diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/azure/run-benchmark-model.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/azure/run-benchmark-model.sh new file mode 100644 index 0000000000000000000000000000000000000000..099519babe723ef8dbaf9d6e278d0531d9c988a0 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/azure/run-benchmark-model.sh @@ -0,0 +1,142 @@ +#!/bin/bash +set -ex + +data_options=" \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --data-path ${DATA_PATH} \ + --data-impl mmap" + +BASE_PATH=$PWD/dataset/ +DATA_PATH=${BASE_PATH}/BookCorpusDataset_text_document +DS_CONFIG=ds_config.json + +# Hostfile path +HF=/job/hostfile + +# Disabling tensor/pipeline parallelism +TP=1 +PP=1 + +# HEADS ~= HIDDEN/128 + +# Model: Benchmark model +NLAYERS=1 +HIDDEN=12288 +HEADS=96 +SEQ=1024 + + +MICRO_BATCH=4 +NODES=2 +GPN=8 +GLOBAL_BATCH=$(( ${GPN} * ${MICRO_BATCH} * ${NODES} )) + +# Initial power scale for loss +SP=15 + +# Uncomment/comment one of the following blocks. + +# For 1T model, start with microbatch=1, try to get 2 and 4. If OOM w/ 4, use cpu-offloading + +# Set to cpu for offloading to cpu for larger models +#OFFLOAD_DEVICE="cpu" +#CPU_OPTIM=" --cpu-optimizer" + +# Set to none and empty string for no cpu offloading +OFFLOAD_DEVICE="none" +CPU_OPTIM=" " + +ZERO_STAGE=3 +OUTPUT_DIR=ds_z_off-${OFFLOAD_DEVICE}_stage_${ZERO_STAGE}_nl${NLAYERS}_hs${HIDDEN}_mb${MICRO_BATCH}_seq${SEQ}_gb${GLOBAL_BATCH}_nodes${NODES} +#OUTPUT_DIR=baseline_nl${NLAYERS}_hs${HIDDEN}_gb${GLOBAL_BATCH}_mb${MICRO_BATCH} +mkdir -p $OUTPUT_DIR + +cat < $DS_CONFIG +{ + "train_batch_size" : $GLOBAL_BATCH, + "train_micro_batch_size_per_gpu": $MICRO_BATCH, + "steps_per_print": 1, + "gradient_accumulation_steps": 1, + "zero_optimization": { + "stage": 3, + "stage3_max_live_parameters": 3e9, + "stage3_max_reuse_distance": 3e9, + "stage3_param_persistence_threshold": 1e5, + "stage3_prefetch_bucket_size": 5e7, + "contiguous_gradients": true, + "overlap_comm": true, + "reduce_bucket_size": 90000000, + "sub_group_size": 1e9, + "offload_optimizer": { + "device": "$OFFLOAD_DEVICE", + "buffer_count": 4, + "pipeline_read": false, + "pipeline_write": false, + "pin_memory": true + } + }, + "gradient_clipping": 1.0, + "fp16": { + "enabled": true, + "initial_scale_power" : $SP, + "loss_scale_window": 1000, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "wall_clock_breakdown": true, + "zero_allow_untested_optimizer": false, + "aio": { + "block_size": 1048576, + "queue_depth": 16, + "single_submit": false, + "overlap_events": true, + "thread_count": 2 + } +} +EOT + +export NCCL_DEBUG=warn + +ds_args=" " +ds_args=" --deepspeed ${ds_args}" +ds_args=" --no-pipeline-parallel ${ds_args}" +ds_args=" --deepspeed_config=$DS_CONFIG ${ds_args}" +ds_args=" --zero-stage=$ZERO_STAGE ${ds_args}" +ds_args=" --deepspeed-activation-checkpointing ${ds_args}" + + + +deepspeed --force_multi --num_nodes=$NODES --hostfile $HF pretrain_gpt.py \ + --tensor-model-parallel-size $TP \ + --pipeline-model-parallel-size $PP \ + --num-layers $NLAYERS \ + --hidden-size $HIDDEN \ + --num-attention-heads $HEADS \ + --seq-length $SEQ \ + --loss-scale $SP \ + --max-position-embeddings $SEQ \ + --micro-batch-size $MICRO_BATCH \ + --global-batch-size $GLOBAL_BATCH \ + --train-iters 50 \ + --lr 6.0e-5 \ + --min-lr 6.0e-6 \ + --lr-decay-style cosine \ + --log-interval 1 \ + --eval-iters 40 \ + --eval-interval 1000 \ + --data-path $DATA_PATH \ + --vocab-file $BASE_PATH/gpt2-vocab.json \ + --merge-file $BASE_PATH/gpt2-merges.txt \ + --save-interval 1000 \ + --split 98,2,0 \ + --clip-grad 1.0 \ + --weight-decay 0.1 \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --init-method-std 0.006 \ + --fp16 \ + --checkpoint-activations \ + --tensorboard-dir $OUTPUT_DIR \ + $CPU_OPTIM $ds_args \ + --exit-interval 5000 | tee ${OUTPUT_DIR}/output.log diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/azureml/Dockerfile.dockerfile b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/azureml/Dockerfile.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2d43612f52a6cf84e3cc47ab493acccab1a47e01 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/azureml/Dockerfile.dockerfile @@ -0,0 +1,14 @@ +FROM mcr.microsoft.com/azureml/aifx/stable-ubuntu2004-cu115-py38-torch1110 + +USER root:root + +RUN pip install pybind11 + +RUN pip install git+https://github.com/microsoft/DeepSpeed.git + +# add a100-topo.xml +RUN mkdir -p /opt/microsoft/ +RUN wget -O /opt/microsoft/a100-topo.xml https://hpcbenchmarks.blob.core.windows.net/bookcorpus/data/a100-topo.xml + +# to use on A100, enable env var below in your job +ENV NCCL_TOPO_FILE="/opt/microsoft/a100-topo.xml" diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/azureml/README.md b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/azureml/README.md new file mode 100644 index 0000000000000000000000000000000000000000..86c7f2adb798c4e3bb2e815d8ba950d89ba7a962 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/azureml/README.md @@ -0,0 +1,14 @@ +## Megatron-DeepSpeed on AzureML +Example script for running Megatron-DeepSpeed using Azure Machine Learning. + +------ + +# Workspace Setup +Setup an AML workspace. Refer to: [set-up doc](https://github.com/Azure/azureml-examples/tree/main/python-sdk#set-up). + +# Dataset Preparation +Create AML Dataset. To run remote AML job, you need to provide AML FileDataset. +Refer to [prepare_dataset script](prepare_dataset.py) to upload .bin and .idx files to blob store and on how to create FileDataset. + +# Training +Run Megatron-DeepSpeed on Azure ML. Refer to [aml_submit script](aml_submit.py). diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/125M-Int8-test-64gpu-distilled-group48.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/125M-Int8-test-64gpu-distilled-group48.sh new file mode 100644 index 0000000000000000000000000000000000000000..5c2a780365dabe743103feb1d489f5dc737811c3 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/125M-Int8-test-64gpu-distilled-group48.sh @@ -0,0 +1,253 @@ +#!/bin/bash +DIR=`pwd` +############################################################################### +### Main configs +## GPT-3 models use 2K sequence length/context window +SEQ_LEN=2048 + +### The "GPT-3 XXX" below are configs from GPT-3 paper +### https://arxiv.org/abs/2005.14165, choose based on +### your desired model size or build your own configs + +## GPT-3 Small 125M +MODEL_SIZE=0.125 +NUM_LAYERS=12 +HIDDEN_SIZE=768 +NUM_ATTN_HEADS=12 +GLOBAL_BATCH_SIZE=256 +# LR=6.0e-4 +LR=6.0e-5 +MIN_LR=6.0e-5 + +# Curriculum learning (CL) enables stable large-batch training +# GLOBAL_BATCH_SIZE=16 # 8x +# LR=6e-4 # 4x + +############################################################################### +### Training duration configs +## The main termination condition, original GPT-3 paper trains for 300B tokens +# TRAIN_TOKENS=300000000000 +TRAIN_TOKENS=5250000000 + +## TRAIN_SAMPLES is another termination condition and also affect the number of +## data samples to be indexed. Since we want to reach the TRAIN_TOKENS +## above, and techniques like curriculum learning has less token in some samples, +## so we just set this config large enough to make sure we have enough +## processed data and don't terminate by TRAIN_SAMPLES. +TRAIN_SAMPLES=$(( ${TRAIN_TOKENS} * 3 / ${SEQ_LEN} )) + +## Another termination condition in minutes. Set it large enough to avoid +## undesired early termination. +EXIT_DURATION=30000000 +############################################################################### +### LR configs +## LR warmup and decay duration, this token-based config is preferable since +## no need to readjust when the batch size/seqlen is changed. +## Original GPT-3 paper uses 375M warmup tokens and 260B decay tokens. +WARMUP_TOKENS=375000000 +LR_DECAY_TOKENS=260000000000 +############################################################################### +### Parallelism configs +## Micro batch size per GPU +## Make sure that BATCH_SIZE <= GLOBAL_BATCH_SIZE*PP_SIZE*MP_SIZE/NUM_GPUS +BATCH_SIZE=4 + +## Model parallelism, 1 is no MP +MP_SIZE=1 + +## Pipeline parallelism. To disable PP, set PP_SIZE to 1 and NO_PP to true. +PP_SIZE=1 +NO_PP="true" + +## ZeRO stage +ZERO_STAGE=0 + +## Total number of GPUs +NUM_GPUS=$(($(ds_ssh nvidia-smi --query-gpu=name --format=csv,noheader | wc -l)-2)) +NUM_GPUS_PERNODE=$(nvidia-smi --query-gpu=name --format=csv,noheader | wc -l) +NUM_NODE=$(( ${NUM_GPUS} / ${NUM_GPUS_PERNODE} )) +DP_SIZE=$(( ${NUM_GPUS} / ${PP_SIZE} / ${MP_SIZE} )) +############################################################################### +### Curriculum learning (CL) configs +## Enable/disable CL +CL_ENABLED="false" +## Consult the tutorial https://www.deepspeed.ai/tutorials/curriculum-learning/ +## for tuning the following configs +CL_START_SEQLEN=72 +CL_AVG_SEQLEN=$(( (${CL_START_SEQLEN} + ${SEQ_LEN}) / 2 )) +CL_TOKENS=60 +CL_STEP=$(( ${CL_TOKENS} * 1000000000 / (${GLOBAL_BATCH_SIZE} * ${CL_AVG_SEQLEN}) )) +############################################################################### +### Misc configs +LOG_INTERVAL=10 +EVAL_ITERS=10 +EVAL_INTERVAL=100 +SAVE_INTERVAL=1000 + +## Standard deviation for weight initialization. Usually larger model needs +## lower std. We used a heuristic equation of sqrt(1/3/HIDDEN_SIZE) from the +## MT-NLG 530B work (https://arxiv.org/pdf/2201.11990.pdf) +INIT_STD=0.02 + +## Activation checkpointing saves GPU memory, but reduces training speed +# ACTIVATION_CHECKPOINT="true" +ACTIVATION_CHECKPOINT="false" + +## Whether or not log optimizer states (norms, max abs values) to tensorboard. +## This is not required for training and might save GPU memory when turned off. +LOG_OPTIMIZER_STATE="true" +############################################################################### +### Output and data configs +current_time=$(date "+%Y.%m.%d-%H.%M.%S") +host="${HOSTNAME}" +NAME="125M10L_Compression_Test_INT8_64gpu_lr6e-5_tokens5.25B_nocl" +if [ "${NO_PP}" = "true" ]; then + NAME="${NAME}-no_pp" +fi +if [ "${CL_ENABLED}" = "true" ]; then + NAME="${NAME}-cl-startseqlen-${CL_START_SEQLEN}-step-${CL_STEP}-token-${CL_TOKENS}B" +fi + +LOG_PATH="log/" +TENSORBOARD_PATH="tensorboard/${NAME}_${host}_${current_time}" +CHECKPOINT_PATH="/blob/users/zheweiyao/compression_library/checkpoint/${NAME}" +mkdir -p ${LOG_PATH} +mkdir -p ${TENSORBOARD_PATH} +mkdir -p ${CHECKPOINT_PATH} + +VOCAB_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-vocab.json +MERGE_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-merges.txt +# Public the Pile dataset, can be downloaded at https://mystic.the-eye.eu/public/AI/pile_neox/ +# For cluster Azure-EastUS-V100-32GB-4, Lab-RR1-V100 +# DATA_PATH=/vc_data_blob/users/conglli/the_pile_public_merged_nopreprocessing/pile_text_document +# For cluster Azure-WestUS3-A100 +DATA_PATH=/blob/data/the_pile_public_merged_nopreprocessing/pile_text_document +############################################################################### +data_options=" \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --data-path ${DATA_PATH} \ + --data-impl mmap" + +megatron_options=" \ + --override-lr-scheduler \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --tensor-model-parallel-size ${MP_SIZE} \ + --init-method-std ${INIT_STD} \ + --lr-decay-tokens ${LR_DECAY_TOKENS} \ + --lr-warmup-tokens ${WARMUP_TOKENS} \ + --micro-batch-size ${BATCH_SIZE} \ + --exit-duration-in-mins ${EXIT_DURATION} \ + --global-batch-size ${GLOBAL_BATCH_SIZE} \ + --num-layers 10 \ + --hidden-size ${HIDDEN_SIZE} \ + --num-attention-heads ${NUM_ATTN_HEADS} \ + --seq-length ${SEQ_LEN} \ + --max-position-embeddings ${SEQ_LEN} \ + --train-tokens ${TRAIN_TOKENS} \ + --train-samples ${TRAIN_SAMPLES} \ + --lr ${LR} \ + --min-lr ${MIN_LR} \ + --lr-decay-style cosine \ + --split 98,2,0 \ + --log-interval ${LOG_INTERVAL} \ + --eval-interval ${EVAL_INTERVAL} \ + --eval-iters ${EVAL_ITERS} \ + --save-interval ${SAVE_INTERVAL} \ + --weight-decay 0.1 \ + --clip-grad 1.0 \ + --hysteresis 2 \ + --num-workers 0 \ + --fp16 \ + --load /blob/users/minjiaz/project/gpt3_distillation/checkpoint/gpt3-kd-staged-alpha1-with-pile-0.125B-lr-2.4e-3-minlr-6.0e-5-bs-2048-gpus-32-zero-0-mp-1-pp-1-no_pp-cl-startseqlen-72-step-27638-token-60B/ \ + --save ${CHECKPOINT_PATH} \ + --tensorboard-queue-size 1 \ + --log-timers-to-tensorboard \ + --log-batch-size-to-tensorboard \ + --no-load-lr-state \ + --reset-iteration \ + --log-validation-ppl-to-tensorboard \ + --tensorboard-dir ${TENSORBOARD_PATH}" + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +megatron_options="${megatron_options} \ + --checkpoint-activations" +fi + +if [ "${LOG_OPTIMIZER_STATE}" = "true" ]; then +megatron_options="${megatron_options} \ + --log-optimizer-states-to-tensorboard" +fi + +template_json="ds_config_gpt_TEMPLATE_compression.json" +config_json="ds_config_${NAME}.json" +if [[ $ZERO_STAGE -gt 0 ]]; then +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/ZERO_STAGE/${ZERO_STAGE}/" \ + | sed "s/PRESCALE_GRAD/false/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} +else +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/ZERO_STAGE/${ZERO_STAGE}/" \ + | sed "s/PRESCALE_GRAD/true/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} +fi + +deepspeed_options=" \ + --deepspeed \ + --deepspeed_config ${config_json} \ + --zero-stage ${ZERO_STAGE} \ + --pipeline-model-parallel-size ${PP_SIZE}" + +if [[ "${NO_PP}" = "true" ]]; then +deepspeed_options="${deepspeed_options} \ + --no-pipeline-parallel" +fi + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +deepspeed_options="${deepspeed_options} \ + --deepspeed-activation-checkpointing" +fi + +## When saving checkpoint to a storage with cache, their could be consistency +## issue of the pointer to latest checkpoint. Here we find the correct pointer +## and broadcast it to all nodes. +ITERATION_FILE="$CHECKPOINT_PATH/latest_checkpointed_iteration.txt" +ITERATION_FILE_2="$CHECKPOINT_PATH/latest" +ITERATION=0 +for (( node = 0; node <= NUM_NODE-1; node++ )) +do + if $(ssh -q worker-"$node" "test -f \"$ITERATION_FILE\""); then + LOCAL_ITERATION=$(ssh -q worker-"$node" cat $ITERATION_FILE) + ITERATION=$(( ${LOCAL_ITERATION} > ${ITERATION} ? ${LOCAL_ITERATION} : ${ITERATION} )) + fi +done +if [[ $ITERATION -gt 0 ]]; then + ITERATION_2="global_step${ITERATION}" + ds_ssh "echo $ITERATION > $ITERATION_FILE" + ds_ssh "echo $ITERATION_2 > $ITERATION_FILE_2" +fi + +run_cmd="deepspeed ${DIR}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &> ${LOG_PATH}/${NAME}.log" +# run_cmd="deepspeed ${DIR}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options}" + +echo ${run_cmd} +eval ${run_cmd} +set +x \ No newline at end of file diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/125M-L10-Int8-test-64gpu-distilled-group48.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/125M-L10-Int8-test-64gpu-distilled-group48.sh new file mode 100644 index 0000000000000000000000000000000000000000..993c421cf8774670bbc04cc63063a30732cdf53b --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/125M-L10-Int8-test-64gpu-distilled-group48.sh @@ -0,0 +1,253 @@ +#!/bin/bash +DIR=`pwd` +############################################################################### +### Main configs +## GPT-3 models use 2K sequence length/context window +SEQ_LEN=2048 + +### The "GPT-3 XXX" below are configs from GPT-3 paper +### https://arxiv.org/abs/2005.14165, choose based on +### your desired model size or build your own configs + +## GPT-3 Small 125M +MODEL_SIZE=0.125 +NUM_LAYERS=12 +HIDDEN_SIZE=768 +NUM_ATTN_HEADS=12 +GLOBAL_BATCH_SIZE=256 +# LR=6.0e-4 +LR=6.0e-5 +MIN_LR=6.0e-5 + +# Curriculum learning (CL) enables stable large-batch training +# GLOBAL_BATCH_SIZE=16 # 8x +# LR=6e-4 # 4x + +############################################################################### +### Training duration configs +## The main termination condition, original GPT-3 paper trains for 300B tokens +# TRAIN_TOKENS=300000000000 +TRAIN_TOKENS=5250000000 + +## TRAIN_SAMPLES is another termination condition and also affect the number of +## data samples to be indexed. Since we want to reach the TRAIN_TOKENS +## above, and techniques like curriculum learning has less token in some samples, +## so we just set this config large enough to make sure we have enough +## processed data and don't terminate by TRAIN_SAMPLES. +TRAIN_SAMPLES=$(( ${TRAIN_TOKENS} * 3 / ${SEQ_LEN} )) + +## Another termination condition in minutes. Set it large enough to avoid +## undesired early termination. +EXIT_DURATION=30000000 +############################################################################### +### LR configs +## LR warmup and decay duration, this token-based config is preferable since +## no need to readjust when the batch size/seqlen is changed. +## Original GPT-3 paper uses 375M warmup tokens and 260B decay tokens. +WARMUP_TOKENS=375000000 +LR_DECAY_TOKENS=260000000000 +############################################################################### +### Parallelism configs +## Micro batch size per GPU +## Make sure that BATCH_SIZE <= GLOBAL_BATCH_SIZE*PP_SIZE*MP_SIZE/NUM_GPUS +BATCH_SIZE=4 + +## Model parallelism, 1 is no MP +MP_SIZE=1 + +## Pipeline parallelism. To disable PP, set PP_SIZE to 1 and NO_PP to true. +PP_SIZE=1 +NO_PP="true" + +## ZeRO stage +ZERO_STAGE=0 + +## Total number of GPUs +NUM_GPUS=$(($(ds_ssh nvidia-smi --query-gpu=name --format=csv,noheader | wc -l)-2)) +NUM_GPUS_PERNODE=$(nvidia-smi --query-gpu=name --format=csv,noheader | wc -l) +NUM_NODE=$(( ${NUM_GPUS} / ${NUM_GPUS_PERNODE} )) +DP_SIZE=$(( ${NUM_GPUS} / ${PP_SIZE} / ${MP_SIZE} )) +############################################################################### +### Curriculum learning (CL) configs +## Enable/disable CL +CL_ENABLED="false" +## Consult the tutorial https://www.deepspeed.ai/tutorials/curriculum-learning/ +## for tuning the following configs +CL_START_SEQLEN=72 +CL_AVG_SEQLEN=$(( (${CL_START_SEQLEN} + ${SEQ_LEN}) / 2 )) +CL_TOKENS=60 +CL_STEP=$(( ${CL_TOKENS} * 1000000000 / (${GLOBAL_BATCH_SIZE} * ${CL_AVG_SEQLEN}) )) +############################################################################### +### Misc configs +LOG_INTERVAL=10 +EVAL_ITERS=10 +EVAL_INTERVAL=100 +SAVE_INTERVAL=1000 + +## Standard deviation for weight initialization. Usually larger model needs +## lower std. We used a heuristic equation of sqrt(1/3/HIDDEN_SIZE) from the +## MT-NLG 530B work (https://arxiv.org/pdf/2201.11990.pdf) +INIT_STD=0.02 + +## Activation checkpointing saves GPU memory, but reduces training speed +# ACTIVATION_CHECKPOINT="true" +ACTIVATION_CHECKPOINT="false" + +## Whether or not log optimizer states (norms, max abs values) to tensorboard. +## This is not required for training and might save GPU memory when turned off. +LOG_OPTIMIZER_STATE="true" +############################################################################### +### Output and data configs +current_time=$(date "+%Y.%m.%d-%H.%M.%S") +host="${HOSTNAME}" +NAME="125M10L_Compression_Test_INT8_64gpu_lr6e-5_tokens5.25B_nocl_alpha" +if [ "${NO_PP}" = "true" ]; then + NAME="${NAME}-no_pp" +fi +if [ "${CL_ENABLED}" = "true" ]; then + NAME="${NAME}-cl-startseqlen-${CL_START_SEQLEN}-step-${CL_STEP}-token-${CL_TOKENS}B" +fi + +LOG_PATH="log/" +TENSORBOARD_PATH="tensorboard/${NAME}_${host}_${current_time}" +CHECKPOINT_PATH="/blob/users/minjiaz/compression_library/checkpoint/${NAME}" +mkdir -p ${LOG_PATH} +mkdir -p ${TENSORBOARD_PATH} +mkdir -p ${CHECKPOINT_PATH} + +VOCAB_PATH=/blob/data/the_pile_public_merged_nopreprocessing/gpt2-vocab.json +MERGE_PATH=/blob/data/the_pile_public_merged_nopreprocessing/gpt2-merges.txt +# Public the Pile dataset, can be downloaded at https://mystic.the-eye.eu/public/AI/pile_neox/ +# For cluster Azure-EastUS-V100-32GB-4, Lab-RR1-V100 +# DATA_PATH=/vc_data_blob/users/conglli/the_pile_public_merged_nopreprocessing/pile_text_document +# For cluster Azure-WestUS3-A100 +DATA_PATH=/blob/data/the_pile_public_merged_nopreprocessing/pile_text_document +############################################################################### +data_options=" \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --data-path ${DATA_PATH} \ + --data-impl mmap" + +megatron_options=" \ + --override-lr-scheduler \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --tensor-model-parallel-size ${MP_SIZE} \ + --init-method-std ${INIT_STD} \ + --lr-decay-tokens ${LR_DECAY_TOKENS} \ + --lr-warmup-tokens ${WARMUP_TOKENS} \ + --micro-batch-size ${BATCH_SIZE} \ + --exit-duration-in-mins ${EXIT_DURATION} \ + --global-batch-size ${GLOBAL_BATCH_SIZE} \ + --num-layers 10 \ + --hidden-size ${HIDDEN_SIZE} \ + --num-attention-heads ${NUM_ATTN_HEADS} \ + --seq-length ${SEQ_LEN} \ + --max-position-embeddings ${SEQ_LEN} \ + --train-tokens ${TRAIN_TOKENS} \ + --train-samples ${TRAIN_SAMPLES} \ + --lr ${LR} \ + --min-lr ${MIN_LR} \ + --lr-decay-style cosine \ + --split 98,2,0 \ + --log-interval ${LOG_INTERVAL} \ + --eval-interval ${EVAL_INTERVAL} \ + --eval-iters ${EVAL_ITERS} \ + --save-interval ${SAVE_INTERVAL} \ + --weight-decay 0.1 \ + --clip-grad 1.0 \ + --hysteresis 2 \ + --num-workers 0 \ + --fp16 \ + --load /blob/users/minjiaz/project/gpt3_distillation/checkpoint/gpt3-kd-staged-alpha1-with-pile-0.125B-lr-2.4e-3-minlr-6.0e-5-bs-2048-gpus-32-zero-0-mp-1-pp-1-no_pp-cl-startseqlen-72-step-27638-token-60B/ \ + --save ${CHECKPOINT_PATH} \ + --tensorboard-queue-size 1 \ + --log-timers-to-tensorboard \ + --log-batch-size-to-tensorboard \ + --no-load-lr-state \ + --reset-iteration \ + --log-validation-ppl-to-tensorboard \ + --tensorboard-dir ${TENSORBOARD_PATH}" + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +megatron_options="${megatron_options} \ + --checkpoint-activations" +fi + +if [ "${LOG_OPTIMIZER_STATE}" = "true" ]; then +megatron_options="${megatron_options} \ + --log-optimizer-states-to-tensorboard" +fi + +template_json="ds_config_gpt_TEMPLATE_compression.json" +config_json="ds_config_${NAME}.json" +if [[ $ZERO_STAGE -gt 0 ]]; then +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/ZERO_STAGE/${ZERO_STAGE}/" \ + | sed "s/PRESCALE_GRAD/false/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} +else +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/ZERO_STAGE/${ZERO_STAGE}/" \ + | sed "s/PRESCALE_GRAD/true/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} +fi + +deepspeed_options=" \ + --deepspeed \ + --deepspeed_config ${config_json} \ + --zero-stage ${ZERO_STAGE} \ + --pipeline-model-parallel-size ${PP_SIZE}" + +if [[ "${NO_PP}" = "true" ]]; then +deepspeed_options="${deepspeed_options} \ + --no-pipeline-parallel" +fi + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +deepspeed_options="${deepspeed_options} \ + --deepspeed-activation-checkpointing" +fi + +## When saving checkpoint to a storage with cache, their could be consistency +## issue of the pointer to latest checkpoint. Here we find the correct pointer +## and broadcast it to all nodes. +ITERATION_FILE="$CHECKPOINT_PATH/latest_checkpointed_iteration.txt" +ITERATION_FILE_2="$CHECKPOINT_PATH/latest" +ITERATION=0 +for (( node = 0; node <= NUM_NODE-1; node++ )) +do + if $(ssh -q worker-"$node" "test -f \"$ITERATION_FILE\""); then + LOCAL_ITERATION=$(ssh -q worker-"$node" cat $ITERATION_FILE) + ITERATION=$(( ${LOCAL_ITERATION} > ${ITERATION} ? ${LOCAL_ITERATION} : ${ITERATION} )) + fi +done +if [[ $ITERATION -gt 0 ]]; then + ITERATION_2="global_step${ITERATION}" + ds_ssh "echo $ITERATION > $ITERATION_FILE" + ds_ssh "echo $ITERATION_2 > $ITERATION_FILE_2" +fi + +run_cmd="deepspeed ${DIR}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &> ${LOG_PATH}/${NAME}.log" +# run_cmd="deepspeed ${DIR}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options}" + +echo ${run_cmd} +eval ${run_cmd} +set +x \ No newline at end of file diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/ds_config_gpt_TEMPLATE.json b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/ds_config_gpt_TEMPLATE.json new file mode 100644 index 0000000000000000000000000000000000000000..295d11ccd7a4742c1e9f297451266f5eb156ce85 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/ds_config_gpt_TEMPLATE.json @@ -0,0 +1,39 @@ +{ + "train_batch_size" : CONFIG_BATCH_SIZE, + "train_micro_batch_size_per_gpu": CONFIG_MBSIZE, + "steps_per_print": LOG_INTERVAL, + + "zero_optimization": { + "stage": ZERO_STAGE, + "elastic_checkpoint": true + }, + + "gradient_clipping": 1.0, + "prescale_gradients": PRESCALE_GRAD, + + "fp16": { + "enabled": CONFIG_FP16_ENABLED, + "loss_scale": 0, + "loss_scale_window": 500, + "hysteresis": 2, + "min_loss_scale": 1, + "initial_scale_power": 11 + }, + + "bf16": { + "enabled": CONFIG_BF16_ENABLED + }, + "curriculum_learning": { + "enabled": CONFIG_CL_ENABLED, + "curriculum_type": "seqlen", + "min_difficulty": CONFIG_CL_MIN, + "max_difficulty": CONFIG_CL_MAX, + "schedule_type": "fixed_linear", + "schedule_config": { + "total_curriculum_step": CONFIG_CL_DURATION, + "difficulty_step": 8 + } + }, + + "wall_clock_breakdown" : false +} diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/ds_config_gpt_TEMPLATE_compression.json b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/ds_config_gpt_TEMPLATE_compression.json new file mode 100644 index 0000000000000000000000000000000000000000..f324d958fc92ff51850b2f8d55f744689e660a04 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/ds_config_gpt_TEMPLATE_compression.json @@ -0,0 +1,87 @@ +{ + "train_batch_size" : CONFIG_BATCH_SIZE, + "train_micro_batch_size_per_gpu": CONFIG_MBSIZE, + "steps_per_print": LOG_INTERVAL, + + "zero_optimization": { + "stage": ZERO_STAGE, + "elastic_checkpoint": true + }, + + "gradient_clipping": 1.0, + "prescale_gradients": PRESCALE_GRAD, + + "fp16": { + "enabled": CONFIG_FP16_ENABLED, + "loss_scale": 0, + "loss_scale_window": 500, + "hysteresis": 2, + "min_loss_scale": 1, + "initial_scale_power": 11 + }, + + "bf16": { + "enabled": CONFIG_BF16_ENABLED + }, + "curriculum_learning": { + "enabled": CONFIG_CL_ENABLED, + "curriculum_type": "seqlen", + "min_difficulty": CONFIG_CL_MIN, + "max_difficulty": CONFIG_CL_MAX, + "schedule_type": "fixed_linear", + "schedule_config": { + "total_curriculum_step": CONFIG_CL_DURATION, + "difficulty_step": 8 + } + }, + + "wall_clock_breakdown" : false, + + "compression_training": { + "weight_quantization": { + "shared_parameters":{ + "enabled": true, + "quantizer_kernel": false, + "schedule_offset": 50, + "quantize_groups": 48, + "quantize_verbose": false, + "quantization_type": "symmetric", + "rounding": "nearest", + "fp16_mixed_quantize":{ + "enabled": false, + "quantize_change_ratio": 0.001 + } + }, + "different_groups":{ + "wq1": { + "params": { + "start_bits": 12, + "target_bits": 4, + "quantization_period": 50 + }, + "modules": [ + "encoder.layers" + ] + } + } + }, + "activation_quantization": { + "shared_parameters":{ + "enabled": true, + "quantization_type": "asymmetric", + "range_calibration": "static", + "schedule_offset": 50 + }, + "different_groups":{ + "aq1": { + "params": { + "bits": 8 + }, + "modules": [ + "encoder.layers" + ] + } + } + } + } +} diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/ds_evalharness.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/ds_evalharness.sh new file mode 100644 index 0000000000000000000000000000000000000000..a1ac63ce25e2a31a492d4deb42ec1f27b00e2528 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/ds_evalharness.sh @@ -0,0 +1,74 @@ +# This is an example zero-shot eval script. Please first read the readme_evalharness.md under the same directory. + +# CHECKPOINT_PATH=/blob/users/minjiaz/compression_library/checkpoint/125M10L_Compression_Test_INT8_64gpu_lr6e-5_tokens5.25B_nocl_alpha-no_pp/global_step2000/ +# CHECKPOINT_PATH=/blob/users/conglli/project/gpt3_with_pile/checkpoint/gpt3-with-pile-0.125B-lr-2.4e-3-minlr-6.0e-5-bs-2048-gpus-64-zero-0-mp-1-pp-1-no_pp-cl-startseqlen-72-step-27638-token-60B/global_step71000/ +# CHECKPOINT_PATH=/blob/users/minjiaz/compression_library/checkpoint/125M12L_Compression_Test_INT8_64gpu_lr6e-5_tokens5.25B_nocl_alpha-no_pp/global_step5000/ +CHECKPOINT_PATH=/blob/users/minjiaz/project/gpt3_distillation/checkpoint/gpt3-kd-test2-alpha1-with-pile-0.125B-lr-2.4e-3-minlr-6.0e-5-bs-2048-gpus-15-zero-0-mp-1-pp-1-no_pp-cl-startseqlen-72-step-27638-token-60B/global_step71426/ +CONFIG_PATH=ds_config_gpt3-with-pile-0.125B-lr-2.4e-3-minlr-6.0e-5-bs-2048-gpus--1-zero-0-mp-1-pp-1-no_pp-cl-startseqlen-72-step-27638-token-60B.json +RESULT_PATH=gpt3-with-pile-0.125B-lr-2.4e-3-minlr-6.0e-5-bs-2048-gpus-128-zero-0-mp-1-pp-1-no_pp-cl-startseqlen-72-step-20728-token-45B_global_step81566.log + +PP_SIZE=1 +TP_SIZE=1 +NO_PP="true" +EP_PARALLEL_SIZE=1 +# Currently eval harness does not support data parallel +# However, for MoE models it's possible to enable a "fake data parallel" +# in order to load experts on multiple gpus. At the same time, it's not +# real data parallel because we load the same data on all gpus. +# On the other hand, it's better to use less number of gpus than training, +# to reduce communication overhead. +NUM_NODE=1 +NUM_GPU_PER_NODE=1 + +# TASKS="lambada" +# WikiText-2, not used in GPT-3 paper but used in GPT-2 paper +TASKS="lambada,wikitext" +# Tasks that appeared in GPT-3 paper (sorted based on the order in paper), plus WikiText-2. +# TASKS="hellaswag,lambada,triviaqa,webqs,winogrande,piqa,arc_challenge,arc_easy,openbookqa,race,boolq,cb,copa,rte,wic,wsc,multirc,record,anli_r1,anli_r2,anli_r3,wikitext" +# All tasks that confirmed to work, there are more tasks on https://github.com/EleutherAI/lm-evaluation-harness that we didn't test. +# TASKS="hellaswag,lambada,triviaqa,webqs,winogrande,piqa,arc_challenge,arc_easy,openbookqa,race,boolq,cb,copa,rte,wic,wsc,multirc,record,anli_r1,anli_r2,anli_r3,wikitext,logiqa,mathqa,mc_taco,mrpc,prost,pubmedqa,qnli,qqp,sciq,sst,wnli" + +VOCAB_FILE=/blob/data/the_pile_public_merged_nopreprocessing/gpt2-vocab.json +MERGE_FILE=/blob/data/the_pile_public_merged_nopreprocessing/gpt2-merges.txt + +export HF_DATASETS_OFFLINE=1 + +# Dummy arguments to make megatron happy. No need to configure them. +# The reason we don't need to configure them and many other arguments is +# because the eval framework will read the arguments from checkpoint file. +MEGATRON_REQUIRED_ARGS="\ + --num-layers -1\ + --hidden-size -1\ + --num-attention-heads -1\ + --seq-length -1 \ + --max-position-embeddings -1 +" + +CMD="../../tasks/eval_harness/evaluate.py \ + --load $CHECKPOINT_PATH\ + --tensor-model-parallel-size $TP_SIZE \ + --pipeline-model-parallel-size $PP_SIZE\ + --moe-expert-parallel-size ${EP_PARALLEL_SIZE} \ + --vocab-file $VOCAB_FILE\ + --merge-file $MERGE_FILE\ + --micro-batch-size 12\ + --no-load-optim \ + --no-load-rng \ + --inference \ + --disable-moe-token-dropping \ + --adaptive_seq_len\ + --eval_fp32\ + --task_list $TASKS\ + --results_path $RESULT_PATH \ + --deepspeed \ + --deepspeed_config $CONFIG_PATH \ + $MEGATRON_REQUIRED_ARGS\ + " + +if [[ "${NO_PP}" = "true" ]]; then +CMD="${CMD} \ + --no-pipeline-parallel" +fi + +LAUNCHER="deepspeed --num_nodes $NUM_NODE --num_gpus $NUM_GPU_PER_NODE" +$LAUNCHER $CMD \ No newline at end of file diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/ds_pretrain_gpt_1.3B_dense_cl_kd.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/ds_pretrain_gpt_1.3B_dense_cl_kd.sh new file mode 100644 index 0000000000000000000000000000000000000000..8b399515557b2323b5e986abc1f20bcd409b21ff --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/ds_pretrain_gpt_1.3B_dense_cl_kd.sh @@ -0,0 +1,322 @@ +#!/bin/bash +DIR=`pwd` +############################################################################### +### Main configs +## GPT-3 models use 2K sequence length/context window +SEQ_LEN=2048 + +### The "GPT-3 XXX" below are configs from GPT-3 paper +### https://arxiv.org/abs/2005.14165, choose based on +### your desired model size or build your own configs + +## GPT-3 Small 125M +# MODEL_SIZE=0.125 +# NUM_LAYERS=12 +# HIDDEN_SIZE=768 +# NUM_ATTN_HEADS=12 +# GLOBAL_BATCH_SIZE=256 +# LR=6.0e-4 +# MIN_LR=6.0e-5 + +## GPT-3 Medium 350M +# MODEL_SIZE=0.35 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1024 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=3.0e-4 +# MIN_LR=3.0e-5 + +## GPT-3 Large 760M +# MODEL_SIZE=0.76 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1536 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=2.5e-4 +# MIN_LR=2.5e-5 + +## GPT-3 XL 1.3B +MODEL_SIZE=1.3 +NUM_LAYERS=24 +HIDDEN_SIZE=2048 +NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=512 +# LR=2.0e-4 +MIN_LR=2.0e-5 + +# Curriculum learning (CL) enables stable large-batch training +GLOBAL_BATCH_SIZE=4096 # 8x +LR=8.0e-4 # 4x + +## GPT-3 2.7B +# MODEL_SIZE=2.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=2560 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=512 +# LR=1.6e-4 +# MIN_LR=1.6e-5 + +## GPT-3 6.7B +# MODEL_SIZE=6.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=4096 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.2e-4 +# MIN_LR=1.2e-5 + +## GPT-3 13B +# MODEL_SIZE=13 +# NUM_LAYERS=40 +# HIDDEN_SIZE=5120 +# NUM_ATTN_HEADS=40 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.0e-4 +# MIN_LR=1.0e-5 + +## GPT-3 175B +# MODEL_SIZE=175 +# NUM_LAYERS=96 +# HIDDEN_SIZE=12288 +# NUM_ATTN_HEADS=96 +# GLOBAL_BATCH_SIZE=1536 +# LR=0.6e-4 +# MIN_LR=0.6e-5 +############################################################################### +### Training duration configs +## The main termination condition, original GPT-3 paper trains for 300B tokens +TRAIN_TOKENS=300000000000 + +## TRAIN_SAMPLES is another termination condition and also affect the number of +## data samples to be indexed. Since we want to reach the TRAIN_TOKENS +## above, and techniques like curriculum learning has less token in some samples, +## so we just set this config large enough to make sure we have enough +## processed data and don't terminate by TRAIN_SAMPLES. +TRAIN_SAMPLES=$(( ${TRAIN_TOKENS} * 3 / ${SEQ_LEN} )) + +## Another termination condition in minutes. Set it large enough to avoid +## undesired early termination. +EXIT_DURATION=30000000 +############################################################################### +### LR configs +## LR warmup and decay duration, this token-based config is preferable since +## no need to readjust when the batch size/seqlen is changed. +## Original GPT-3 paper uses 375M warmup tokens and 260B decay tokens. +WARMUP_TOKENS=375000000 +LR_DECAY_TOKENS=260000000000 +############################################################################### +### Parallelism configs +## Micro batch size per GPU +## Make sure that BATCH_SIZE <= GLOBAL_BATCH_SIZE*PP_SIZE*MP_SIZE/NUM_GPUS +BATCH_SIZE=16 + +## Model parallelism, 1 is no MP +MP_SIZE=2 + +## Pipeline parallelism. To disable PP, set PP_SIZE to 1 and NO_PP to true. +PP_SIZE=1 +NO_PP="true" + +## ZeRO stage +ZERO_STAGE=0 + +## Total number of GPUs +NUM_GPUS=$(($(ds_ssh nvidia-smi --query-gpu=name --format=csv,noheader | wc -l)-2)) +NUM_GPUS_PERNODE=$(nvidia-smi --query-gpu=name --format=csv,noheader | wc -l) +NUM_NODE=$(( ${NUM_GPUS} / ${NUM_GPUS_PERNODE} )) +DP_SIZE=$(( ${NUM_GPUS} / ${PP_SIZE} / ${MP_SIZE} )) +############################################################################### +### Curriculum learning (CL) configs +## Enable/disable CL +CL_ENABLED="true" +## Consult the tutorial https://www.deepspeed.ai/tutorials/curriculum-learning/ +## for tuning the following configs +CL_START_SEQLEN=80 +CL_AVG_SEQLEN=$(( (${CL_START_SEQLEN} + ${SEQ_LEN}) / 2 )) +CL_TOKENS=60 +CL_STEP=$(( ${CL_TOKENS} * 1000000000 / (${GLOBAL_BATCH_SIZE} * ${CL_AVG_SEQLEN}) )) +############################################################################### +### Misc configs +LOG_INTERVAL=10 +EVAL_ITERS=10 +EVAL_INTERVAL=100 +SAVE_INTERVAL=10000 + +## Standard deviation for weight initialization. Usually larger model needs +## lower std. We used a heuristic equation of sqrt(1/3/HIDDEN_SIZE) from the +## MT-NLG 530B work (https://arxiv.org/pdf/2201.11990.pdf) +INIT_STD=0.013 + +## Activation checkpointing saves GPU memory, but reduces training speed +ACTIVATION_CHECKPOINT="true" +# ACTIVATION_CHECKPOINT="false" + +## Whether or not log optimizer states (norms, max abs values) to tensorboard. +## This is not required for training and might save GPU memory when turned off. +LOG_OPTIMIZER_STATE="true" +############################################################################### +### Output and data configs +current_time=$(date "+%Y.%m.%d-%H.%M.%S") +host="${HOSTNAME}" +NAME="gpt3-kd-with-pile-${MODEL_SIZE}B-lr-${LR}-minlr-${MIN_LR}-bs-${GLOBAL_BATCH_SIZE}-gpus-${NUM_GPUS}-zero-${ZERO_STAGE}-mp-${MP_SIZE}-pp-${PP_SIZE}" +if [ "${NO_PP}" = "true" ]; then + NAME="${NAME}-no_pp" +fi +if [ "${CL_ENABLED}" = "true" ]; then + NAME="${NAME}-cl-startseqlen-${CL_START_SEQLEN}-step-${CL_STEP}-token-${CL_TOKENS}B" +fi + +LOG_PATH="log/" +TENSORBOARD_PATH="tensorboard/${NAME}_${host}_${current_time}" +CHECKPOINT_PATH="/blob/users/minjiaz/project/gpt3_distillation/checkpoint/${NAME}" +mkdir -p ${LOG_PATH} +mkdir -p ${TENSORBOARD_PATH} +mkdir -p ${CHECKPOINT_PATH} + +### KD configs +KD_BETA_CE=1 +CHECKPOINT_PATH_TEACHER="/blob/users/conglli/project/gpt3_with_pile/checkpoint/gpt3-with-pile-1.3B-lr-8.0e-4-minlr-2.0e-5-bs-4096-gpus-128-zero-0-mp-2-pp-1-no_pp-cl-startseqlen-80-step-13767-token-60B/" +CHECKPOINT_PATH_SAVE="/blob/users/minjiaz/project/gpt3_distillation/checkpoint/${NAME}" + +mkdir -p ${CHECKPOINT_PATH_SAVE} + +VOCAB_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-vocab.json +MERGE_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-merges.txt +# Public the Pile dataset, can be downloaded at https://mystic.the-eye.eu/public/AI/pile_neox/ +# DATA_PATH=/data/the_pile_public_merged_nopreprocessing/pile_text_document +# For cluster Azure-WestUS3-A100 +DATA_PATH=/blob/data/the_pile_public_merged_nopreprocessing/pile_text_document + +############################################################################### +data_options=" \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --data-path ${DATA_PATH} \ + --data-impl mmap" + +megatron_options=" \ + --override-lr-scheduler \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --tensor-model-parallel-size ${MP_SIZE} \ + --init-method-std ${INIT_STD} \ + --lr-decay-tokens ${LR_DECAY_TOKENS} \ + --lr-warmup-tokens ${WARMUP_TOKENS} \ + --micro-batch-size ${BATCH_SIZE} \ + --exit-duration-in-mins ${EXIT_DURATION} \ + --global-batch-size ${GLOBAL_BATCH_SIZE} \ + --num-layers 21 \ + --hidden-size ${HIDDEN_SIZE} \ + --num-attention-heads ${NUM_ATTN_HEADS} \ + --seq-length ${SEQ_LEN} \ + --max-position-embeddings ${SEQ_LEN} \ + --train-tokens ${TRAIN_TOKENS} \ + --train-samples ${TRAIN_SAMPLES} \ + --lr ${LR} \ + --min-lr ${MIN_LR} \ + --lr-decay-style cosine \ + --split 98,2,0 \ + --log-interval ${LOG_INTERVAL} \ + --eval-interval ${EVAL_INTERVAL} \ + --eval-iters ${EVAL_ITERS} \ + --save-interval ${SAVE_INTERVAL} \ + --weight-decay 0.1 \ + --clip-grad 1.0 \ + --hysteresis 2 \ + --num-workers 0 \ + --fp16 \ + --load ${CHECKPOINT_PATH} \ + --save ${CHECKPOINT_PATH_SAVE} \ + --kd \ + --kd-beta-ce ${KD_BETA_CE} \ + --num-layers-teacher ${NUM_LAYERS} \ + --hidden-size-teacher ${HIDDEN_SIZE} \ + --num-attention-heads-teacher ${NUM_ATTN_HEADS} \ + --load-teacher ${CHECKPOINT_PATH_TEACHER} \ + --tensorboard-queue-size 1 \ + --log-timers-to-tensorboard \ + --log-batch-size-to-tensorboard \ + --log-validation-ppl-to-tensorboard \ + --tensorboard-dir ${TENSORBOARD_PATH}" + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +megatron_options="${megatron_options} \ + --checkpoint-activations" +fi + +if [ "${LOG_OPTIMIZER_STATE}" = "true" ]; then +megatron_options="${megatron_options} \ + --log-optimizer-states-to-tensorboard" +fi + +template_json="ds_config_gpt_TEMPLATE.json" +config_json="ds_config_${NAME}.json" +if [[ $ZERO_STAGE -gt 0 ]]; then +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/ZERO_STAGE/${ZERO_STAGE}/" \ + | sed "s/PRESCALE_GRAD/false/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} +else +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/ZERO_STAGE/${ZERO_STAGE}/" \ + | sed "s/PRESCALE_GRAD/true/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} +fi + +deepspeed_options=" \ + --deepspeed \ + --deepspeed_config ${config_json} \ + --zero-stage ${ZERO_STAGE} \ + --pipeline-model-parallel-size ${PP_SIZE}" + +if [[ "${NO_PP}" = "true" ]]; then +deepspeed_options="${deepspeed_options} \ + --no-pipeline-parallel" +fi + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +deepspeed_options="${deepspeed_options} \ + --deepspeed-activation-checkpointing" +fi + +## When saving checkpoint to a storage with cache, their could be consistency +## issue of the pointer to latest checkpoint. Here we find the correct pointer +## and broadcast it to all nodes. +ITERATION_FILE="$CHECKPOINT_PATH/latest_checkpointed_iteration.txt" +ITERATION_FILE_2="$CHECKPOINT_PATH/latest" +ITERATION=0 +for (( node = 0; node <= NUM_NODE-1; node++ )) +do + if $(ssh -q worker-"$node" "test -f \"$ITERATION_FILE\""); then + LOCAL_ITERATION=$(ssh -q worker-"$node" cat $ITERATION_FILE) + ITERATION=$(( ${LOCAL_ITERATION} > ${ITERATION} ? ${LOCAL_ITERATION} : ${ITERATION} )) + fi +done +if [[ $ITERATION -gt 0 ]]; then + ITERATION_2="global_step${ITERATION}" + ds_ssh "echo $ITERATION > $ITERATION_FILE" + ds_ssh "echo $ITERATION_2 > $ITERATION_FILE_2" +fi + +run_cmd="deepspeed ${DIR}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &> ${LOG_PATH}/${NAME}_${host}_${current_time}.log" +echo ${run_cmd} +eval ${run_cmd} +set +x diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/ds_pretrain_gpt_125M_dense_cl_kd.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/ds_pretrain_gpt_125M_dense_cl_kd.sh new file mode 100644 index 0000000000000000000000000000000000000000..761a8f60618a6212bbe58bc3bcab7be5c7e57375 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/ds_pretrain_gpt_125M_dense_cl_kd.sh @@ -0,0 +1,323 @@ +#!/bin/bash +DIR=`pwd` +############################################################################### +### Main configs +## GPT-3 models use 2K sequence length/context window +SEQ_LEN=2048 + +### The "GPT-3 XXX" below are configs from GPT-3 paper +### https://arxiv.org/abs/2005.14165, choose based on +### your desired model size or build your own configs + +## GPT-3 Small 125M +MODEL_SIZE=0.125 +NUM_LAYERS=12 +HIDDEN_SIZE=768 +NUM_ATTN_HEADS=12 +# GLOBAL_BATCH_SIZE=256 +# LR=6.0e-4 +MIN_LR=6.0e-5 + +# Curriculum learning (CL) enables stable large-batch training +GLOBAL_BATCH_SIZE=2048 # 8x +LR=2.4e-3 # 4x + +## GPT-3 Medium 350M +# MODEL_SIZE=0.35 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1024 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=3.0e-4 +# MIN_LR=3.0e-5 + +## GPT-3 Large 760M +# MODEL_SIZE=0.76 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1536 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=2.5e-4 +# MIN_LR=2.5e-5 + +## GPT-3 XL 1.3B +# MODEL_SIZE=1.3 +# NUM_LAYERS=24 +# HIDDEN_SIZE=2048 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=512 +# LR=2.0e-4 +# MIN_LR=2.0e-5 + +## GPT-3 2.7B +# MODEL_SIZE=2.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=2560 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=512 +# LR=1.6e-4 +# MIN_LR=1.6e-5 + +## GPT-3 6.7B +# MODEL_SIZE=6.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=4096 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.2e-4 +# MIN_LR=1.2e-5 + +## GPT-3 13B +# MODEL_SIZE=13 +# NUM_LAYERS=40 +# HIDDEN_SIZE=5120 +# NUM_ATTN_HEADS=40 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.0e-4 +# MIN_LR=1.0e-5 + +## GPT-3 175B +# MODEL_SIZE=175 +# NUM_LAYERS=96 +# HIDDEN_SIZE=12288 +# NUM_ATTN_HEADS=96 +# GLOBAL_BATCH_SIZE=1536 +# LR=0.6e-4 +# MIN_LR=0.6e-5 +############################################################################### +### Training duration configs +## The main termination condition, original GPT-3 paper trains for 300B tokens +TRAIN_TOKENS=300000000000 + +## TRAIN_SAMPLES is another termination condition and also affect the number of +## data samples to be indexed. Since we want to reach the TRAIN_TOKENS +## above, and techniques like curriculum learning has less token in some samples, +## so we just set this config large enough to make sure we have enough +## processed data and don't terminate by TRAIN_SAMPLES. +TRAIN_SAMPLES=$(( ${TRAIN_TOKENS} * 3 / ${SEQ_LEN} )) + +## Another termination condition in minutes. Set it large enough to avoid +## undesired early termination. +EXIT_DURATION=30000000 +############################################################################### +### LR configs +## LR warmup and decay duration, this token-based config is preferable since +## no need to readjust when the batch size/seqlen is changed. +## Original GPT-3 paper uses 375M warmup tokens and 260B decay tokens. +WARMUP_TOKENS=375000000 +LR_DECAY_TOKENS=260000000000 +############################################################################### +### Parallelism configs +## Micro batch size per GPU +## Make sure that BATCH_SIZE <= GLOBAL_BATCH_SIZE*PP_SIZE*MP_SIZE/NUM_GPUS +BATCH_SIZE=8 + +## Model parallelism, 1 is no MP +MP_SIZE=1 + +## Pipeline parallelism. To disable PP, set PP_SIZE to 1 and NO_PP to true. +PP_SIZE=1 +NO_PP="true" + +## ZeRO stage +ZERO_STAGE=0 + +## Total number of GPUs +NUM_GPUS=$(($(ds_ssh nvidia-smi --query-gpu=name --format=csv,noheader | wc -l)-2)) +NUM_GPUS_PERNODE=$(nvidia-smi --query-gpu=name --format=csv,noheader | wc -l) +NUM_NODE=$(( ${NUM_GPUS} / ${NUM_GPUS_PERNODE} )) +DP_SIZE=$(( ${NUM_GPUS} / ${PP_SIZE} / ${MP_SIZE} )) +############################################################################### +### Curriculum learning (CL) configs +## Enable/disable CL +CL_ENABLED="true" +## Consult the tutorial https://www.deepspeed.ai/tutorials/curriculum-learning/ +## for tuning the following configs +CL_START_SEQLEN=72 +CL_AVG_SEQLEN=$(( (${CL_START_SEQLEN} + ${SEQ_LEN}) / 2 )) +CL_TOKENS=60 +CL_STEP=$(( ${CL_TOKENS} * 1000000000 / (${GLOBAL_BATCH_SIZE} * ${CL_AVG_SEQLEN}) )) +############################################################################### +### Misc configs +LOG_INTERVAL=10 +EVAL_ITERS=10 +EVAL_INTERVAL=100 +SAVE_INTERVAL=10000 + +## Standard deviation for weight initialization. Usually larger model needs +## lower std. We used a heuristic equation of sqrt(1/3/HIDDEN_SIZE) from the +## MT-NLG 530B work (https://arxiv.org/pdf/2201.11990.pdf) +INIT_STD=0.02 + +## Activation checkpointing saves GPU memory, but reduces training speed +ACTIVATION_CHECKPOINT="true" +# ACTIVATION_CHECKPOINT="false" + +## Whether or not log optimizer states (norms, max abs values) to tensorboard. +## This is not required for training and might save GPU memory when turned off. +LOG_OPTIMIZER_STATE="true" +############################################################################### +### Output and data configs +current_time=$(date "+%Y.%m.%d-%H.%M.%S") +host="${HOSTNAME}" +NAME="gpt3-kd-test1-alpha1-with-pile-${MODEL_SIZE}B-lr-${LR}-minlr-${MIN_LR}-bs-${GLOBAL_BATCH_SIZE}-gpus-${NUM_GPUS}-zero-${ZERO_STAGE}-mp-${MP_SIZE}-pp-${PP_SIZE}" +if [ "${NO_PP}" = "true" ]; then + NAME="${NAME}-no_pp" +fi +if [ "${CL_ENABLED}" = "true" ]; then + NAME="${NAME}-cl-startseqlen-${CL_START_SEQLEN}-step-${CL_STEP}-token-${CL_TOKENS}B" +fi + +LOG_PATH="log/" +TENSORBOARD_PATH="tensorboard/${NAME}_${host}_${current_time}" +CHECKPOINT_PATH="/blob/users/minjiaz/project/gpt3_distillation/checkpoint/${NAME}" +mkdir -p ${LOG_PATH} +mkdir -p ${TENSORBOARD_PATH} +mkdir -p ${CHECKPOINT_PATH} + +### KD configs +KD_BETA_CE=1 +CHECKPOINT_PATH_TEACHER="/blob/users/conglli/project/gpt3_with_pile/checkpoint/gpt3-with-pile-0.125B-lr-2.4e-3-minlr-6.0e-5-bs-2048-gpus-64-zero-0-mp-1-pp-1-no_pp-cl-startseqlen-72-step-27638-token-60B/" +CHECKPOINT_PATH_SAVE="/blob/users/minjiaz/project/gpt3_distillation/checkpoint/${NAME}" + +mkdir -p ${CHECKPOINT_PATH_SAVE} + + +VOCAB_PATH=/blob/data/the_pile_public_merged_nopreprocessing/gpt2-vocab.json +MERGE_PATH=/blob/data/the_pile_public_merged_nopreprocessing/gpt2-merges.txt +# Public the Pile dataset, can be downloaded at https://mystic.the-eye.eu/public/AI/pile_neox/ +# For cluster Azure-EastUS-V100-32GB-4, Lab-RR1-V100 +# DATA_PATH=/vc_data_blob/users/conglli/the_pile_public_merged_nopreprocessing/pile_text_document +# For cluster Azure-WestUS3-A100 +DATA_PATH=/blob/data/the_pile_public_merged_nopreprocessing/pile_text_document +############################################################################### +data_options=" \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --data-path ${DATA_PATH} \ + --data-impl mmap" + +megatron_options=" \ + --override-lr-scheduler \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --tensor-model-parallel-size ${MP_SIZE} \ + --init-method-std ${INIT_STD} \ + --lr-decay-tokens ${LR_DECAY_TOKENS} \ + --lr-warmup-tokens ${WARMUP_TOKENS} \ + --micro-batch-size ${BATCH_SIZE} \ + --exit-duration-in-mins ${EXIT_DURATION} \ + --global-batch-size ${GLOBAL_BATCH_SIZE} \ + --num-layers 10 \ + --hidden-size ${HIDDEN_SIZE} \ + --num-attention-heads ${NUM_ATTN_HEADS} \ + --seq-length ${SEQ_LEN} \ + --max-position-embeddings ${SEQ_LEN} \ + --train-tokens ${TRAIN_TOKENS} \ + --train-samples ${TRAIN_SAMPLES} \ + --lr ${LR} \ + --min-lr ${MIN_LR} \ + --lr-decay-style cosine \ + --split 98,2,0 \ + --log-interval ${LOG_INTERVAL} \ + --eval-interval ${EVAL_INTERVAL} \ + --eval-iters ${EVAL_ITERS} \ + --save-interval ${SAVE_INTERVAL} \ + --weight-decay 0.1 \ + --clip-grad 1.0 \ + --hysteresis 2 \ + --num-workers 0 \ + --fp16 \ + --load ${CHECKPOINT_PATH} \ + --save ${CHECKPOINT_PATH_SAVE} \ + --kd \ + --kd-beta-ce ${KD_BETA_CE} \ + --num-layers-teacher ${NUM_LAYERS} \ + --hidden-size-teacher ${HIDDEN_SIZE} \ + --num-attention-heads-teacher ${NUM_ATTN_HEADS} \ + --load-teacher ${CHECKPOINT_PATH_TEACHER} \ + --tensorboard-queue-size 1 \ + --log-timers-to-tensorboard \ + --log-batch-size-to-tensorboard \ + --log-validation-ppl-to-tensorboard \ + --tensorboard-dir ${TENSORBOARD_PATH}" + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +megatron_options="${megatron_options} \ + --checkpoint-activations" +fi + +if [ "${LOG_OPTIMIZER_STATE}" = "true" ]; then +megatron_options="${megatron_options} \ + --log-optimizer-states-to-tensorboard" +fi + +template_json="ds_config_gpt_TEMPLATE.json" +config_json="ds_config_${NAME}.json" +if [[ $ZERO_STAGE -gt 0 ]]; then +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/ZERO_STAGE/${ZERO_STAGE}/" \ + | sed "s/PRESCALE_GRAD/false/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} +else +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/ZERO_STAGE/${ZERO_STAGE}/" \ + | sed "s/PRESCALE_GRAD/true/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} +fi + +deepspeed_options=" \ + --deepspeed \ + --deepspeed_config ${config_json} \ + --zero-stage ${ZERO_STAGE} \ + --pipeline-model-parallel-size ${PP_SIZE}" + +if [[ "${NO_PP}" = "true" ]]; then +deepspeed_options="${deepspeed_options} \ + --no-pipeline-parallel" +fi + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +deepspeed_options="${deepspeed_options} \ + --deepspeed-activation-checkpointing" +fi + +## When saving checkpoint to a storage with cache, their could be consistency +## issue of the pointer to latest checkpoint. Here we find the correct pointer +## and broadcast it to all nodes. +ITERATION_FILE="$CHECKPOINT_PATH/latest_checkpointed_iteration.txt" +ITERATION_FILE_2="$CHECKPOINT_PATH/latest" +ITERATION=0 +for (( node = 0; node <= NUM_NODE-1; node++ )) +do + if $(ssh -q worker-"$node" "test -f \"$ITERATION_FILE\""); then + LOCAL_ITERATION=$(ssh -q worker-"$node" cat $ITERATION_FILE) + ITERATION=$(( ${LOCAL_ITERATION} > ${ITERATION} ? ${LOCAL_ITERATION} : ${ITERATION} )) + fi +done +if [[ $ITERATION -gt 0 ]]; then + ITERATION_2="global_step${ITERATION}" + ds_ssh "echo $ITERATION > $ITERATION_FILE" + ds_ssh "echo $ITERATION_2 > $ITERATION_FILE_2" +fi + +run_cmd="deepspeed ${DIR}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &> ${LOG_PATH}/${NAME}_${host}_${current_time}.log" +echo ${run_cmd} +eval ${run_cmd} +set +x diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/ds_pretrain_gpt_350M_dense_kd.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/ds_pretrain_gpt_350M_dense_kd.sh new file mode 100644 index 0000000000000000000000000000000000000000..1844a75ba1f4e847503bde04062182a754d5d7cb --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/compression/ds_pretrain_gpt_350M_dense_kd.sh @@ -0,0 +1,349 @@ +#!/bin/bash +DIR=`pwd` +############################################################################### +### Main configs +## GPT-3 models use 2K sequence length/context window +SEQ_LEN=2048 + +### The "GPT-3 XXX" below are configs from GPT-3 paper +### https://arxiv.org/abs/2005.14165, choose based on +### your desired model size or build your own configs + +## GPT-3 Small 125M +# MODEL_SIZE=0.125 +# NUM_LAYERS=12 +# HIDDEN_SIZE=768 +# NUM_ATTN_HEADS=12 +# GLOBAL_BATCH_SIZE=256 +# LR=6.0e-4 +# MIN_LR=6.0e-5 + +## GPT-3 Medium 350M +MODEL_SIZE=0.35 +NUM_LAYERS=24 +HIDDEN_SIZE=1024 +NUM_ATTN_HEADS=16 +GLOBAL_BATCH_SIZE=256 +LR=3.0e-4 +MIN_LR=3.0e-5 + +## GPT-3 Large 760M +# MODEL_SIZE=0.76 +# NUM_LAYERS=24 +# HIDDEN_SIZE=1536 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=256 +# LR=2.5e-4 +# MIN_LR=2.5e-5 + +## GPT-3 XL 1.3B +# MODEL_SIZE=1.3 +# NUM_LAYERS=24 +# HIDDEN_SIZE=2048 +# NUM_ATTN_HEADS=16 +# GLOBAL_BATCH_SIZE=512 +# LR=2.0e-4 +# MIN_LR=2.0e-5 + +## GPT-3 2.7B +# MODEL_SIZE=2.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=2560 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=512 +# LR=1.6e-4 +# MIN_LR=1.6e-5 + +## GPT-3 6.7B +# MODEL_SIZE=6.7 +# NUM_LAYERS=32 +# HIDDEN_SIZE=4096 +# NUM_ATTN_HEADS=32 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.2e-4 +# MIN_LR=1.2e-5 + +## GPT-3 13B +# MODEL_SIZE=13 +# NUM_LAYERS=40 +# HIDDEN_SIZE=5120 +# NUM_ATTN_HEADS=40 +# GLOBAL_BATCH_SIZE=1024 +# LR=1.0e-4 +# MIN_LR=1.0e-5 + +## GPT-3 175B +# MODEL_SIZE=175 +# NUM_LAYERS=96 +# HIDDEN_SIZE=12288 +# NUM_ATTN_HEADS=96 +# GLOBAL_BATCH_SIZE=1536 +# LR=0.6e-4 +# MIN_LR=0.6e-5 +############################################################################### +### Training duration configs +## The main termination condition, original GPT-3 paper trains for 300B tokens +## For MoE model, we found sometimes training a bit more to 330B tokens helps +TRAIN_TOKENS=300000000000 +# TRAIN_TOKENS=330000000000 + +## TRAIN_SAMPLES is another termination condition and also affect the number of +## data samples to be indexed. Since we want to reach the TRAIN_TOKENS +## above, and techniques like curriculum learning has less token in some steps, +## so we just set this config large enough to make sure we have enough +## processed data and don't terminate by TRAIN_SAMPLES. +TRAIN_SAMPLES=$(( ${TRAIN_TOKENS} * 3 / ${SEQ_LEN} )) + +## Another termination condition in minutes. Set it large enough to avoid +## undesired early termination. +EXIT_DURATION=30000000 +############################################################################### +### LR configs +## LR warmup and decay duration, this token-based config is preferable since +## no need to readjust when the batch size/seqlen is changed. +## Original GPT-3 paper uses 375M warmup tokens and 260B decay tokens. +## For MoE model, we found that setting the decay token to 300B helps. +WARMUP_TOKENS=375000000 +LR_DECAY_TOKENS=260000000000 +# LR_DECAY_TOKENS=300000000000 +############################################################################### +### Parallelism configs +## Micro batch size per GPU +## Make sure that BATCH_SIZE <= GLOBAL_BATCH_SIZE*PP_SIZE*MP_SIZE/NUM_GPUS +BATCH_SIZE=4 + +## Model parallelism, 1 is no MP +## Currently MoE models have divergence issue when MP > 1. +MP_SIZE=1 + +## Pipeline parallelism +## Currently we don't support PP for MoE. To disable PP, set PP_SIZE +## to 1 and use the "--no-pipeline-parallel" arg. +PP_SIZE=1 +NUM_GPUS=64 +############################################################################### +### MoE configs +## Number of experts. EP_SIZE 1 means dense model without MoE +EP_SIZE=1 +# EP_SIZE=128 + +if [[ $EP_SIZE -gt $NUM_GPUS ]]; then + EP_PARALLEL_SIZE=$NUM_GPUS +else + EP_PARALLEL_SIZE=$EP_SIZE +fi + +## Original GPT-3 model always set min LR at 10% of max LR. For MoE model, we +## found that lower LR and min LR (than the base dense model) helps. +## For 1.3B MoE-128 model we used LR=1.2e-4 and MIN_LR=1.0e-6. +## For 350M MoE-128 model we used LR=2.0e-4 and MIN_LR=2.0e-6, but they are not +## heavily tuned. +# LR=2.0e-4 +# MIN_LR=2e-06 + +## Coefficient for MoE loss. We find that 0.01 is a good value at least for +## 1.3B MoE-128 model +MLC=0.01 + +## Below configs adjust the MoE expert token capacity limit during training and +## eval. To completely disable capacity limit, set MOE_DROP_TOKEN to false. +## Larger capacity factor or disabling capacity limit could improve training +## convergence, but will also reduce training throughput. +MOE_TRAIN_CAP_FACTOR=1.0 +MOE_EVAL_CAP_FACTOR=1.0 +MOE_MIN_CAP=4 +MOE_DROP_TOKEN="true" +# MOE_DROP_TOKEN="false" +############################################################################### +### Curriculum learning (CL) configs +## Enable/disable CL +CL_ENABLED="false" +## Consult the tutorial https://www.deepspeed.ai/tutorials/curriculum-learning/ +## for tuning the following configs +CL_START_SEQLEN=80 +CL_AVG_SEQLEN=$(( (${CL_START_SEQLEN} + ${SEQ_LEN}) / 2 )) +CL_TOKENS=60 +CL_TOKENS=$((${CL_TOKENS} * 1000000000)) +CL_STEP=$(( ${CL_TOKENS} / (${GLOBAL_BATCH_SIZE} * ${CL_AVG_SEQLEN}) )) +############################################################################### +### Misc configs +LOG_INTERVAL=10 +EVAL_ITERS=10 +EVAL_INTERVAL=100 +SAVE_INTERVAL=1000 + +## Standard deviation for weight initialization +## We used 0.014 for 350M/1.3B dense/MoE models, and used 0.01 for 6.7B +## dense model. Usually larger model needs lower std. +INIT_STD=0.014 +# INIT_STD=0.01 + +## Activation checkpointing saves GPU memory, but reduces training speed +ACTIVATION_CHECKPOINT="true" +# ACTIVATION_CHECKPOINT="false" +############################################################################### +### Output and data configs +current_time=$(date "+%Y.%m.%d-%H.%M.%S") +host="${HOSTNAME}" +NAME="gpt-kd-${MODEL_SIZE}B-lr-${LR}-minlr-${MIN_LR}-bs-${GLOBAL_BATCH_SIZE}-gpus-${NUM_GPUS}-mp-${MP_SIZE}-pp-${PP_SIZE}" +if [[ $EP_SIZE -gt 1 ]]; then + NAME="${NAME}-ep-${EP_SIZE}-mlc-${MLC}-cap-${MOE_TRAIN_CAP_FACTOR}-drop-${MOE_DROP_TOKEN}" +fi +if [ "${CL_ENABLED}" = "true" ]; then + NAME="${NAME}-cl-${CL_START_SEQLEN}-${CL_STEP}" +fi + +OUTPUT_BASEPATH=$DIR/output +mkdir -p "${OUTPUT_BASEPATH}/tensorboard/" +mkdir -p "${OUTPUT_BASEPATH}/checkpoint/" +mkdir -p "${OUTPUT_BASEPATH}/log/" +TENSORBOARD_DIR="${OUTPUT_BASEPATH}/tensorboard/${NAME}_${host}_${current_time}" +mkdir -p ${TENSORBOARD_DIR} +## Note that for MoE model with billion-scale base model, the checkpoint can be +## as large as TB-scale which normal NFS cannot handle efficiently. +CHECKPOINT_PATH="${OUTPUT_BASEPATH}/checkpoint/${NAME}" + +# USE_INTERNAL_DATA="true" +USE_INTERNAL_DATA="false" + +if [ "${USE_INTERNAL_DATA}" = "true" ]; then + ## The internal data is only accessible within Microsoft + ## For cluster Azure-EastUS-V100-32GB-4, Azure-WestUS3-A100 + # BASE_DATA_PATH=/vc_data/Megatron-LM/data + # DATA_HOME="/vc_data/pile-cc1-cc2-shuf" + ## For cluster Lab-RR1-V100 + BASE_DATA_PATH=/data/Megatron-LM/data + DATA_HOME="/turing-ssd/users/conglli/data/pile-cc1-cc2-shuf" + ## For cluster Azure-CentralUS-A100 + # BASE_DATA_PATH=/data/Megatron-LM/data + # DATA_HOME=/vc_data_1/users/amawa/blended + + VOCAB_PATH=${BASE_DATA_PATH}/gpt2-vocab.json + MERGE_PATH=${BASE_DATA_PATH}/gpt2-merges.txt + ARX="${DATA_HOME}/ArXiv_ftfy_cleaned_id_shuf_text_document" + BC2="${DATA_HOME}/BookCorpus2_ftfy_cleaned_id_shuf_text_document" + B3="${DATA_HOME}/Books3_ftfy_cleaned_id_shuf_text_document" + CC2020="${DATA_HOME}/CC-2020-50_id_cleaned_shuf_text_document" + CC2021="${DATA_HOME}/CC-2021-04_id_cleaned_shuf_text_document" + GIT="${DATA_HOME}/Github_ftfy_id_shuf_text_document" + GUT="${DATA_HOME}/Gutenberg_PG-19_ftfy_cleaned_id_cleaned_shuf_text_document" + NIH="${DATA_HOME}/NIH_ExPorter_ftfy_id_shuf_text_document" + OWT2="${DATA_HOME}/OpenWebText2_ftfy_cleaned_id_shuf_text_document" + PCC="${DATA_HOME}/Pile-CC_id_cleaned_shuf_text_document" + PM="${DATA_HOME}/PubMed_Abstracts_ftfy_id_shuf_text_document" + RN="${DATA_HOME}/rn_dedup_shuf_cleaned_0.7_cleaned_shuf_text_document" + SE="${DATA_HOME}/StackExchange_ftfy_id_shuf_text_document" + ST="${DATA_HOME}/stories_dedup0.7_shuf_cleaned_shuf_text_document" + WIK="${DATA_HOME}/Wikipedia_en_ftfy_id_shuf_text_document" + DATA_BLEND="0.14336 ${B3} 0.08962 ${RN} 0.19336 ${OWT2} 0.05689 ${SE} \ + 0.00859 ${ST} 0.02897 ${PM} 0.04771 ${WIK} 0.00873 ${GUT} 0.01007 ${BC2} \ + 0.00208 ${NIH} 0.13017 ${CC2020} 0.09446 ${PCC} 0.15652 ${CC2021} \ + 0.01359 ${ARX} 0.01588 ${GIT}" +else + VOCAB_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-vocab.json + MERGE_PATH=/data/the_pile_public_merged_nopreprocessing/gpt2-merges.txt + # Public the Pile dataset, can be downloaded at https://mystic.the-eye.eu/public/AI/pile_neox/ + DATA_BLEND=/data/the_pile_public_merged_nopreprocessing/pile_text_document +fi +############################################################################### +data_options=" \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --data-path ${DATA_BLEND} \ + --data-impl mmap" + +megatron_options=" \ + --override-lr-scheduler \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --tensor-model-parallel-size ${MP_SIZE} \ + --moe-expert-parallel-size ${EP_PARALLEL_SIZE} \ + --num-experts ${EP_SIZE} \ + --moe-loss-coeff ${MLC} \ + --moe-train-capacity-factor ${MOE_TRAIN_CAP_FACTOR} \ + --moe-eval-capacity-factor ${MOE_EVAL_CAP_FACTOR} \ + --moe-min-capacity ${MOE_MIN_CAP} \ + --init-method-std ${INIT_STD} \ + --lr-decay-tokens ${LR_DECAY_TOKENS} \ + --lr-warmup-tokens ${WARMUP_TOKENS} \ + --micro-batch-size ${BATCH_SIZE} \ + --exit-duration-in-mins ${EXIT_DURATION} \ + --global-batch-size ${GLOBAL_BATCH_SIZE} \ + --num-layers ${NUM_LAYERS} \ + --hidden-size ${HIDDEN_SIZE} \ + --num-attention-heads ${NUM_ATTN_HEADS} \ + --seq-length ${SEQ_LEN} \ + --max-position-embeddings ${SEQ_LEN} \ + --train-tokens ${TRAIN_TOKENS} \ + --train-samples ${TRAIN_SAMPLES} \ + --lr ${LR} \ + --min-lr ${MIN_LR} \ + --lr-decay-style cosine \ + --split 98,2,0 \ + --log-interval ${LOG_INTERVAL} \ + --eval-interval ${EVAL_INTERVAL} \ + --eval-iters ${EVAL_ITERS} \ + --save-interval ${SAVE_INTERVAL} \ + --weight-decay 0.1 \ + --clip-grad 1.0 \ + --hysteresis 2 \ + --num-workers 0 \ + --fp16 \ + --load ${CHECKPOINT_PATH} \ + --save ${CHECKPOINT_PATH} \ + --tensorboard-queue-size 1 \ + --log-timers-to-tensorboard \ + --log-batch-size-to-tensorboard \ + --log-validation-ppl-to-tensorboard \ + --tensorboard-dir ${TENSORBOARD_DIR}" + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +megatron_options="${megatron_options} \ + --checkpoint-activations" +fi + +if [[ $EP_SIZE -gt 1 ]]; then +megatron_options="${megatron_options} \ + --create-moe-param-group" +fi + +if [ "${MOE_DROP_TOKEN}" = "false" ]; then +megatron_options="${megatron_options} \ + --disable-moe-token-dropping" +fi + +template_json="ds_config_gpt_TEMPLATE.json" +config_json="ds_config_gpt_${NAME}.json" +sed "s/CONFIG_BATCH_SIZE/${GLOBAL_BATCH_SIZE}/" ${template_json} \ + | sed "s/CONFIG_MBSIZE/${BATCH_SIZE}/" \ + | sed "s/LOG_INTERVAL/${LOG_INTERVAL}/" \ + | sed "s/ZERO_STAGE/0/" \ + | sed "s/PRESCALE_GRAD/true/" \ + | sed "s/CONFIG_FP16_ENABLED/true/" \ + | sed "s/CONFIG_BF16_ENABLED/false/" \ + | sed "s/CONFIG_CL_ENABLED/${CL_ENABLED}/" \ + | sed "s/CONFIG_CL_MIN/${CL_START_SEQLEN}/" \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CL_STEP}/" \ + > ${config_json} + +deepspeed_options=" \ + --deepspeed \ + --deepspeed_config ${config_json} \ + --pipeline-model-parallel-size ${PP_SIZE}" + +# Currently MoE is not compatible with pipeline parallel +if [[ $EP_SIZE -gt 1 ]]; then +deepspeed_options="${deepspeed_options} \ + --no-pipeline-parallel" +fi + +if [ "${ACTIVATION_CHECKPOINT}" = "true" ]; then +deepspeed_options="${deepspeed_options} \ + --deepspeed-activation-checkpointing" +fi + +run_cmd="deepspeed ${DIR}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &> ${OUTPUT_BASEPATH}/log/${NAME}_${host}_${current_time}.log" +echo ${run_cmd} +eval ${run_cmd} +set +x diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/curriculum_learning/README.md b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/curriculum_learning/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a80e3510cc7c2c4435c5fadc98c1e7dd17239d20 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/curriculum_learning/README.md @@ -0,0 +1 @@ +This is an example of how to use DeepSpeed's curriculum learning (CL) feature which provides faster and more stable language model pre-training. Currently it is only integrated for GPT pre-training. Note that there are two curriculum learning examples in two different repos for Megatron-LM GPT-2 pre-training. Both of them have some unique features and limitations. See details in our [tutorial](https://www.deepspeed.ai/tutorials/curriculum-learning/). For technical details please refer to our [paper](https://arxiv.org/abs/2108.06084). \ No newline at end of file diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/curriculum_learning/ds_train.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/curriculum_learning/ds_train.sh new file mode 100644 index 0000000000000000000000000000000000000000..aac11ab034bd075dec482d611556f4ee7191c70f --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/curriculum_learning/ds_train.sh @@ -0,0 +1,37 @@ +# # baseline +# CONFIG=baseline +# TAG=baseline +# MODEL_SIZE=1558 +# LR=1.5e-4 +# BSZ=512 +# SEQ_LEN=1024 +# MP_SIZE=1 +# SEED=1234 +# SAVE_INTERVAL=5000 +# NUM_ITER=600000 +# NUM_TOKEN=157286400000 +# LR_DECAY_TOKEN=157286400000 +# LR_WARMUP_ITER=3000 +# CONFIG_TEMPLATE=false +# CURRICULUM_STEP=0 +# CURRICULUM_MIN=0 + +# curriculum learning +CONFIG=curriculum_fixed_linear +MODEL_SIZE=1558 +LR=6e-4 +BSZ=4096 +SEQ_LEN=1024 +MP_SIZE=1 +SEED=1234 +SAVE_INTERVAL=1000 +NUM_ITER=75000 +NUM_TOKEN=157286400000 +LR_DECAY_TOKEN=157286400000 +LR_WARMUP_ITER=3000 +CONFIG_TEMPLATE=true +CURRICULUM_STEP=45000 +CURRICULUM_MIN=64 +TAG="${CONFIG}_s${CURRICULUM_MIN}to${SEQ_LEN}_step${CURRICULUM_STEP}" + +bash ds_pretrain_gpt2.sh $CONFIG $TAG $MODEL_SIZE $LR $BSZ $SEQ_LEN $MP_SIZE $SEED $SAVE_INTERVAL $NUM_ITER $NUM_TOKEN $LR_DECAY_TOKEN $LR_WARMUP_ITER $CONFIG_TEMPLATE $CURRICULUM_STEP $CURRICULUM_MIN diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/curriculum_learning/ds_zero_stage_1_config_baseline.json b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/curriculum_learning/ds_zero_stage_1_config_baseline.json new file mode 100644 index 0000000000000000000000000000000000000000..71494f3748e790df5592f09bf17839dd1db7af64 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/curriculum_learning/ds_zero_stage_1_config_baseline.json @@ -0,0 +1,26 @@ +{ + "train_batch_size": 512, + "gradient_accumulation_steps": 1, + "steps_per_print": 1, + "zero_optimization": { + "stage": 1 + }, + "optimizer": { + "type": "Adam", + "params": { + "lr": 0.00015, + "max_grad_norm": 1.0, + "betas": [0.9, 0.95] + } + }, + "gradient_clipping": 1.0, + "fp16": { + "enabled": true, + "loss_scale": 0, + "loss_scale_window": 1000, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "wall_clock_breakdown": false, + "zero_allow_untested_optimizer": false +} diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/curriculum_learning/ds_zero_stage_1_config_curriculum_fixed_linear.json b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/curriculum_learning/ds_zero_stage_1_config_curriculum_fixed_linear.json new file mode 100644 index 0000000000000000000000000000000000000000..e2f9478308735ed111ce735a0c22cb5e2eb305c7 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/curriculum_learning/ds_zero_stage_1_config_curriculum_fixed_linear.json @@ -0,0 +1,37 @@ +{ + "train_batch_size": 512, + "gradient_accumulation_steps": 1, + "steps_per_print": 1, + "zero_optimization": { + "stage": 1 + }, + "optimizer": { + "type": "Adam", + "params": { + "lr": 0.00015, + "max_grad_norm": 1.0, + "betas": [0.9, 0.95] + } + }, + "gradient_clipping": 1.0, + "fp16": { + "enabled": true, + "loss_scale": 0, + "loss_scale_window": 1000, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "wall_clock_breakdown": false, + "zero_allow_untested_optimizer": false, + "curriculum_learning": { + "enabled": true, + "curriculum_type": "seqlen", + "min_difficulty": CONFIG_CL_MIN, + "max_difficulty": CONFIG_CL_MAX, + "schedule_type": "fixed_linear", + "schedule_config": { + "total_curriculum_step": CONFIG_CL_DURATION, + "difficulty_step": 8 + } + } +} diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/evaluate_zeroshot_gpt.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/evaluate_zeroshot_gpt.sh new file mode 100644 index 0000000000000000000000000000000000000000..96fd28f3a7b490e5fe4d9390ff7f775d2442cf03 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/evaluate_zeroshot_gpt.sh @@ -0,0 +1,38 @@ +#!/bin/bash + +WORLD_SIZE=8 + +DISTRIBUTED_ARGS="--nproc_per_node $WORLD_SIZE \ + --nnodes 1 \ + --node_rank 0 \ + --master_addr localhost \ + --master_port 6000" + +TASK="LAMBADA" + +VALID_DATA= +VOCAB_FILE=gpt2-vocab.json +MERGE_FILE=gpt2-merges.txt +CHECKPOINT=checkpoints/gpt2_345m + + +python -m torch.distributed.launch $DISTRIBUTED_ARGS ./tasks/main.py \ + --task $TASK \ + --valid-data $VALID_DATA \ + --tokenizer-type GPT2BPETokenizer \ + --strict-lambada \ + --vocab-file $VOCAB_FILE \ + --merge-file $MERGE_FILE \ + --load $CHECKPOINT \ + --tensor-model-parallel-size 1 \ + --num-layers 24 \ + --hidden-size 1024 \ + --num-attention-heads 16 \ + --batch-size 8 \ + --checkpoint-activations \ + --seq-length 1024 \ + --max-position-embeddings 1024 \ + --log-interval 10 \ + --fp16 \ + --no-load-optim \ + --no-load-rng diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/generate_text.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/generate_text.sh new file mode 100644 index 0000000000000000000000000000000000000000..63501fc67cbc9c80b60fa091d94dea2cdac49a93 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/generate_text.sh @@ -0,0 +1,48 @@ +#!/bin/bash +export TORCH_CUDA_ARCH_LIST=8.6+PTX +CHECKPOINT_PATH=checkpoints/gpt2_345m +VOCAB_FILE=gpt2-vocab.json +MERGE_FILE=gpt2-merges.txt +b=8 +mp=1 +experts=2 +nodes=1 +gpus=1 + + +use_tutel="" +#use_tutel="--use-tutel" + + +#ds_inference="" +ds_inference="--ds-inference" + +launch_cmd="deepspeed --num_nodes $nodes --num_gpus $gpus" +L=24 +H=2048 +A=16 +#experts1=${experts[$k]} +program_cmd="tools/generate_samples_gpt.py \ + --tensor-model-parallel-size $mp \ + --num-layers $L \ + --hidden-size $H \ + --num-attention-heads $A \ + --max-position-embeddings 1024 \ + --tokenizer-type GPT2BPETokenizer \ + --fp16 \ + --num-experts ${experts} \ + --mlp-type standard \ + --micro-batch-size $b \ + --seq-length 10 \ + --out-seq-length 10 \ + --temperature 1.0 \ + --vocab-file $VOCAB_FILE \ + --merge-file $MERGE_FILE \ + --genfile unconditional_samples.json \ + --top_p 0.9 \ + --log-interval 1 \ + --num-samples $((100*$b)) + $use_tutel $ds_inference" + +echo $launch_cmd $program_cmd +$launch_cmd $program_cmd diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/merge_mp_bert.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/merge_mp_bert.sh new file mode 100644 index 0000000000000000000000000000000000000000..1383433284bc79a70785305c0628e3d80aeb92d0 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/merge_mp_bert.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +TENSOR_MODEL_PARALLEL_SIZE=2 + +VOCAB_FILE=bert-vocab.txt +CHECKPOINT_PATH=checkpoints/bert_345m + +WORLD_SIZE=$TENSOR_MODEL_PARALLEL_SIZE python tools/merge_mp_partitions.py \ + --model-type BERT \ + --tensor-model-parallel-size $TENSOR_MODEL_PARALLEL_SIZE \ + --tokenizer-type BertWordPieceLowerCase \ + --vocab-file $VOCAB_FILE \ + --num-layers 24 \ + --hidden-size 1024 \ + --num-attention-heads 16 \ + --seq-length 512 \ + --max-position-embeddings 512 \ + --load $CHECKPOINT_PATH diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_bert_distributed.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_bert_distributed.sh new file mode 100644 index 0000000000000000000000000000000000000000..a833c5a948820866cae7c9efc36b7d8f8ad6bfa7 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_bert_distributed.sh @@ -0,0 +1,44 @@ +#!/bin/bash + +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=_text_sentence +CHECKPOINT_PATH= + +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_bert.py \ + --num-layers 24 \ + --hidden-size 1024 \ + --num-attention-heads 16 \ + --micro-batch-size 4 \ + --global-batch-size 32 \ + --seq-length 512 \ + --max-position-embeddings 512 \ + --train-iters 1000000 \ + --save $CHECKPOINT_PATH \ + --load $CHECKPOINT_PATH \ + --data-path $DATA_PATH \ + --vocab-file bert-vocab.txt \ + --data-impl mmap \ + --split 949,50,1 \ + --distributed-backend nccl \ + --lr 0.0001 \ + --lr-decay-style linear \ + --min-lr 1.0e-5 \ + --lr-decay-iters 990000 \ + --weight-decay 1e-2 \ + --clip-grad 1.0 \ + --lr-warmup-fraction .01 \ + --log-interval 100 \ + --save-interval 10000 \ + --eval-interval 1000 \ + --eval-iters 10 \ + --fp16 diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_bert_distributed_with_mp.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_bert_distributed_with_mp.sh new file mode 100644 index 0000000000000000000000000000000000000000..4c50dcc259e7ee59255dccf666df0be46acb9a6c --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_bert_distributed_with_mp.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +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=_text_sentence +VOCAB_FILE= +CHECKPOINT_PATH= + +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_bert.py \ + --tensor-model-parallel-size 2 \ + --pipeline-model-parallel-size 2 \ + --num-layers 24 \ + --hidden-size 1024 \ + --num-attention-heads 16 \ + --micro-batch-size 2 \ + --global-batch-size 16 \ + --max-position-embeddings 512 \ + --train-iters 1000000 \ + --save $CHECKPOINT_PATH \ + --load $CHECKPOINT_PATH \ + --data-path $DATA_PATH \ + --vocab-file $VOCAB_FILE \ + --data-impl mmap \ + --split 949,50,1 \ + --distributed-backend nccl \ + --lr 0.0001 \ + --lr-decay-style linear \ + --min-lr 1.0e-5 \ + --lr-decay-iters 990000 \ + --weight-decay 1e-2 \ + --clip-grad 1.0 \ + --lr-warmup-fraction .01 \ + --log-interval 100 \ + --save-interval 10000 \ + --eval-interval 1000 \ + --eval-iters 10 \ + --fp16 diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_gpt.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_gpt.sh new file mode 100644 index 0000000000000000000000000000000000000000..ed070861f1b98189d11e6532a87491354a759c57 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_gpt.sh @@ -0,0 +1,41 @@ +#! /bin/bash + +# Runs the "345M" parameter model + +RANK=0 +WORLD_SIZE=1 + +DATA_PATH=_text_document +CHECKPOINT_PATH= + + +python pretrain_gpt.py \ + --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 500000 \ + --lr-decay-iters 320000 \ + --save $CHECKPOINT_PATH \ + --load $CHECKPOINT_PATH \ + --data-path $DATA_PATH \ + --vocab-file gpt2-vocab.json \ + --merge-file gpt2-merges.txt \ + --data-impl mmap \ + --split 949,50,1 \ + --distributed-backend nccl \ + --lr 0.00015 \ + --min-lr 1.0e-5 \ + --lr-decay-style cosine \ + --weight-decay 1e-2 \ + --clip-grad 1.0 \ + --lr-warmup-fraction .01 \ + --checkpoint-activations \ + --log-interval 100 \ + --save-interval 10000 \ + --eval-interval 1000 \ + --eval-iters 10 \ + --fp16 diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_gpt3_175B.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_gpt3_175B.sh new file mode 100644 index 0000000000000000000000000000000000000000..ad0d244d7b9502d34875fbb2b59b975b34e476af --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_gpt3_175B.sh @@ -0,0 +1,65 @@ +#!/bin/bash + + +#SBATCH --nodes=128 --exclusive --ntasks-per-node=8 --job-name=megatron_gpt3_175b + + +DIR=`pwd` +DATETIME=`date +'date_%y-%m-%d_time_%H-%M-%S'` +mkdir -p $DIR/logs + + +DATASET_1="" +DATASET_2="" +DATASET_3="" +DATASET="0.2 ${DATASET_1} 0.3 ${DATASET_2} 0.5 ${DATASET_3}" + + +options=" \ + --tensor-model-parallel-size 8 \ + --pipeline-model-parallel-size 16 \ + --num-layers 96 \ + --hidden-size 12288 \ + --num-attention-heads 96 \ + --seq-length 2048 \ + --max-position-embeddings 2048 \ + --micro-batch-size 1 \ + --global-batch-size 1536 \ + --rampup-batch-size 16 16 5859375 \ + --train-samples 146484375 \ + --lr-decay-samples 126953125 \ + --lr-warmup-samples 183105 \ + --lr 6.0e-5 \ + --min-lr 6.0e-6 \ + --lr-decay-style cosine \ + --log-interval 10 \ + --eval-iters 40 \ + --eval-interval 1000 \ + --data-path ${DATASET} \ + --vocab-file \ + --merge-file \ + --save-interval 1000 \ + --save \ + --load \ + --split 98,2,0 \ + --clip-grad 1.0 \ + --weight-decay 0.1 \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --init-method-std 0.006 \ + --tensorboard-dir \ + --fp16 \ + --checkpoint-activations " + + +run_cmd="python -u ${DIR}/pretrain_gpt.py $@ ${options}" + + +srun -l \ + --container-image "nvcr.io/nvidia/pytorch:20.12-py3" \ + --container-mounts "" \ + --output=$DIR/logs/%x_%j_$DATETIME.log sh -c "${run_cmd}" + + +set +x + diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_gpt_distributed.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_gpt_distributed.sh new file mode 100644 index 0000000000000000000000000000000000000000..1b4518604ea1258afac2e89cd2ff6a46aa747315 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_gpt_distributed.sh @@ -0,0 +1,48 @@ +#! /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=_text_document +CHECKPOINT_PATH= + +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 \ + --num-layers 24 \ + --hidden-size 1024 \ + --num-attention-heads 16 \ + --micro-batch-size 8 \ + --global-batch-size 64 \ + --seq-length 1024 \ + --max-position-embeddings 1024 \ + --train-iters 500000 \ + --lr-decay-iters 320000 \ + --save $CHECKPOINT_PATH \ + --load $CHECKPOINT_PATH \ + --data-path $DATA_PATH \ + --vocab-file gpt2-vocab.json \ + --merge-file 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 100 \ + --save-interval 10000 \ + --eval-interval 1000 \ + --eval-iters 10 \ + --fp16 diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_gpt_distributed_with_mp.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_gpt_distributed_with_mp.sh new file mode 100644 index 0000000000000000000000000000000000000000..c67db4c4548660d0ec5c11662335d81675926dde --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_gpt_distributed_with_mp.sh @@ -0,0 +1,50 @@ +#! /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=_text_document +CHECKPOINT_PATH= + +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 2 \ + --pipeline-model-parallel-size 2 \ + --num-layers 24 \ + --hidden-size 1024 \ + --num-attention-heads 16 \ + --micro-batch-size 4 \ + --global-batch-size 16 \ + --seq-length 1024 \ + --max-position-embeddings 1024 \ + --train-iters 500000 \ + --lr-decay-iters 320000 \ + --save $CHECKPOINT_PATH \ + --load $CHECKPOINT_PATH \ + --data-path $DATA_PATH \ + --vocab-file gpt2-vocab.json \ + --merge-file 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 100 \ + --save-interval 10000 \ + --eval-interval 1000 \ + --eval-iters 10 \ + --fp16 diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_ict.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_ict.sh new file mode 100644 index 0000000000000000000000000000000000000000..8cba0f08ba4c0f9d1697d721ae8e65dd28c1c914 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_ict.sh @@ -0,0 +1,44 @@ +#! /bin/bash + +# Runs the "217M" parameter biencoder model for ICT retriever + +RANK=0 +WORLD_SIZE=1 + +PRETRAINED_BERT_PATH= +TEXT_DATA_PATH= +TITLE_DATA_PATH= +CHECKPOINT_PATH= + + +python pretrain_ict.py \ + --num-layers 12 \ + --hidden-size 768 \ + --num-attention-heads 12 \ + --tensor-model-parallel-size 1 \ + --micro-batch-size 32 \ + --seq-length 256 \ + --max-position-embeddings 512 \ + --train-iters 100000 \ + --vocab-file bert-vocab.txt \ + --tokenizer-type BertWordPieceLowerCase \ + --DDP-impl torch \ + --bert-load ${PRETRAINED_BERT_PATH} \ + --log-interval 100 \ + --eval-interval 1000 \ + --eval-iters 10 \ + --retriever-report-topk-accuracies 1 5 10 20 100 \ + --retriever-score-scaling \ + --load $CHECKPOINT_PATH \ + --save $CHECKPOINT_PATH \ + --data-path ${TEXT_DATA_PATH} \ + --titles-data-path ${TITLE_DATA_PATH} \ + --lr 0.0001 \ + --lr-decay-style linear \ + --weight-decay 1e-2 \ + --clip-grad 1.0 \ + --lr-warmup-fraction 0.01 \ + --save-interval 4000 \ + --exit-interval 8000 \ + --query-in-block-prob 0.1 \ + --fp16 diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_t5.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_t5.sh new file mode 100644 index 0000000000000000000000000000000000000000..71fea8489a7b7a96974ab019e5c54cab9d2f5f47 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/pretrain_t5.sh @@ -0,0 +1,38 @@ +#!/bin/bash + +RANK=0 +WORLD_SIZE=1 +DATA_PATH= +VOCAB_FILE= +CHECKPOINT_PATH= + +python pretrain_t5.py \ + --num-layers 12 \ + --hidden-size 768 \ + --num-attention-heads 12 \ + --kv-channels 64 \ + --ffn-hidden-size 3072 \ + --encoder-seq-length 512 \ + --decoder-seq-length 128 \ + --micro-batch-size 16 \ + --global-batch-size 2048 \ + --max-position-embeddings 512 \ + --train-iters 1000000 \ + --lr-decay-iters 1000000 \ + --save $CHECKPOINT_PATH \ + --load $CHECKPOINT_PATH \ + --data-path $DATA_PATH \ + --vocab-file $VOCAB_FILE \ + --data-impl mmap \ + --split 949,50,1 \ + --lr 0.0001 \ + --min-lr 0.00001 \ + --lr-decay-style linear \ + --lr-warmup-fraction .01 \ + --weight-decay 1e-2 \ + --clip-grad 1.0 \ + --log-interval 100 \ + --save-interval 10000 \ + --eval-interval 1000 \ + --eval-iters 10 \ + --fp16 diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/run_deepspeed_example.sh b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/run_deepspeed_example.sh new file mode 100644 index 0000000000000000000000000000000000000000..909cdf671387090e40097c9ace8b606fc9f5a948 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/examples/run_deepspeed_example.sh @@ -0,0 +1,84 @@ +#!/bin/bash +set -ex + +BASE_PATH=/vc_data/Megatron-LM/data +DATA_PATH=${BASE_PATH}/indexed_datasets/megatron +DS_CONFIG=ds_config.json + +TP=1 +PP=1 +NLAYERS=24 +HIDDEN=512 + +GLOBAL_BATCH=64 +MICRO_BATCH=4 + +ZERO_STAGE=2 + +OUTPUT_DIR=ds_z${ZERO_STAGE}_nl${NLAYERS}_hs${HIDDEN}_gb${GLOBAL_BATCH}_mb${MICRO_BATCH} +#OUTPUT_DIR=baseline_nl${NLAYERS}_hs${HIDDEN}_gb${GLOBAL_BATCH}_mb${MICRO_BATCH} +mkdir -p $OUTPUT_DIR + +cat < $DS_CONFIG +{ + "train_batch_size" : $GLOBAL_BATCH, + "train_micro_batch_size_per_gpu": $MICRO_BATCH, + "steps_per_print": 1, + + "zero_optimization": { + "stage": $ZERO_STAGE + }, + + "fp16": { + "enabled": true, + "initial_scale_power": 12 + }, + + "wall_clock_breakdown" : true +} +EOT + +export NCCL_DEBUG=warn + +ds_args="" +ds_args=" --deepspeed ${ds_args}" +ds_args=" --no-pipeline-parallel ${ds_args}" +ds_args=" --deepspeed_config=$DS_CONFIG ${ds_args}" +ds_args=" --zero-stage=$ZERO_STAGE ${ds_args}" +ds_args=" --deepspeed-activation-checkpointing ${ds_args}" + + +deepspeed pretrain_gpt.py \ + --tensor-model-parallel-size $TP \ + --pipeline-model-parallel-size $PP \ + --num-layers $NLAYERS \ + --hidden-size $HIDDEN \ + --num-attention-heads 16 \ + --seq-length 256 \ + --loss-scale 12 \ + --max-position-embeddings 1024 \ + --micro-batch-size 4 \ + --global-batch-size 1024 \ + --train-iters 1000 \ + --lr 6.0e-5 \ + --min-lr 6.0e-6 \ + --lr-decay-style cosine \ + --log-interval 1 \ + --eval-iters 40 \ + --eval-interval 1000 \ + --data-path $DATA_PATH \ + --vocab-file $BASE_PATH/gpt2-vocab.json \ + --merge-file $BASE_PATH/gpt2-merges.txt \ + --save-interval 1000 \ + --split 98,2,0 \ + --clip-grad 1.0 \ + --weight-decay 0.1 \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --init-method-std 0.006 \ + --fp16 \ + --checkpoint-activations \ + --tensorboard-dir $OUTPUT_DIR \ + $ds_args \ + --exit-interval 5000 | tee ${OUTPUT_DIR}/output.log + diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/images/cases_april2021.png b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/images/cases_april2021.png new file mode 100644 index 0000000000000000000000000000000000000000..9b70f655a7d887e799ef5e3a33b773df7451d8ee --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/images/cases_april2021.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6785b9aedc153052dd91f29ce806893326a64382591ebf6d74f0fe63c3b78250 +size 163078 diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/data_utils.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/data_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..866a5e69a233d9a9a68a837e156ebb240be6bfee --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/data_utils.py @@ -0,0 +1,118 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed 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. + +""" Tasks data utility.""" + +import re +import numpy as np + + +def clean_text(text): + """Remove new lines and multiple spaces and adjust end of sentence dot.""" + + text = text.replace("\n", " ") + text = re.sub(r'\s+', ' ', text) + for _ in range(3): + text = text.replace(' . ', '. ') + + return text + + +def build_sample(ids, types, paddings, label, unique_id): + """Convert to numpy and return a sample consumed by the batch producer.""" + + ids_np = np.array(ids, dtype=np.int64) + types_np = np.array(types, dtype=np.int64) + paddings_np = np.array(paddings, dtype=np.int64) + sample = ({'text': ids_np, + 'types': types_np, + 'padding_mask': paddings_np, + 'label': int(label), + 'uid': int(unique_id)}) + + return sample + + +def build_tokens_types_paddings_from_text(text_a, text_b, + tokenizer, max_seq_length): + """Build token types and paddings, trim if needed, and pad if needed.""" + + text_a_ids = tokenizer.tokenize(text_a) + text_b_ids = None + if text_b is not None: + text_b_ids = tokenizer.tokenize(text_b) + + return build_tokens_types_paddings_from_ids(text_a_ids, text_b_ids, + max_seq_length, tokenizer.cls, + tokenizer.sep, tokenizer.pad) + + +def build_tokens_types_paddings_from_ids(text_a_ids, text_b_ids, max_seq_length, + cls_id, sep_id, pad_id): + """Build token types and paddings, trim if needed, and pad if needed.""" + + ids = [] + types = [] + paddings = [] + + # [CLS]. + ids.append(cls_id) + types.append(0) + paddings.append(1) + + # A. + len_text_a = len(text_a_ids) + ids.extend(text_a_ids) + types.extend([0] * len_text_a) + paddings.extend([1] * len_text_a) + + # [SEP]. + ids.append(sep_id) + types.append(0) + paddings.append(1) + + # B. + if text_b_ids is not None: + len_text_b = len(text_b_ids) + ids.extend(text_b_ids) + types.extend([1] * len_text_b) + paddings.extend([1] * len_text_b) + + # Cap the size. + trimmed = False + if len(ids) >= max_seq_length: + max_seq_length_m1 = max_seq_length - 1 + ids = ids[0:max_seq_length_m1] + types = types[0:max_seq_length_m1] + paddings = paddings[0:max_seq_length_m1] + trimmed = True + + # [SEP]. + if (text_b_ids is not None) or trimmed: + ids.append(sep_id) + if text_b_ids is None: + types.append(0) + else: + types.append(1) + paddings.append(1) + + # Padding. + padding_length = max_seq_length - len(ids) + if padding_length > 0: + ids.extend([pad_id] * padding_length) + types.extend([pad_id] * padding_length) + paddings.extend([0] * padding_length) + + return ids, types, paddings diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/detok.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/detok.py new file mode 100644 index 0000000000000000000000000000000000000000..fe6dfd50907901325c500a105d74a0ea1bf69650 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/detok.py @@ -0,0 +1,73 @@ +import os +import sys +import torch +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), + os.path.pardir))) + +from tqdm import tqdm +from megatron import get_args +from megatron import get_tokenizer +from megatron.initialize import initialize_megatron +from pretrain_gpt import train_valid_test_datasets_provider +from megatron.training import build_train_valid_test_data_iterators + + +def get_detok_args(parser): + group = parser.add_argument_group(title='detokenizer') + group.add_argument('--detokenizer_output', + type=str, + required=True, + help='detokenizer output path') + return parser + + +def process_split(split, dataset, out_path): + print(f'Processing {split}') + tokenizer = get_tokenizer() + + full_text = [] + for batch in tqdm(dataset, total=len(dataset)): + tokens = batch['text'].reshape(-1).tolist() + text = tokenizer.detokenize(tokens) + full_text.append(text) + + out_name = os.path.join(out_path, f'{split}.text') + print(f'Writing to {out_name}') + with open(out_name, 'w') as f: + f.writelines(full_text) + + +def main(): + + # below arguments are to force the full dataset according to the + # train/valid/test split based on args.split + forced_args = { + "micro_batch_size": 1, + "train_samples": None, + "train_iters": 1, + "eval_iters": 1, + "eval_interval": 2, + "use_seq_len_plus_one_tokens": False + } + + initialize_megatron(extra_args_provider=get_detok_args, args_defaults=forced_args) + torch.distributed.barrier() + + # after parsing, we have to force again the required args + args = get_args() + for name, value in forced_args.items(): + setattr(args, name, value) + + # create train/valid/test split based on args.split + args.iteration = 0 + train_iter, valid_iter, test_iter = build_train_valid_test_data_iterators( + train_valid_test_datasets_provider) + + os.makedirs(args.detokenizer_output, exist_ok=True) + process_split('test', test_iter._dataset, args.detokenizer_output) + process_split('valid', valid_iter._dataset, args.detokenizer_output) + process_split('train', train_iter._dataset, args.detokenizer_output) + + +if __name__ == '__main__': + main() diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/ensemble_classifier.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/ensemble_classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..c2333b70154b5761b47bcb7cdf50e11c3d500dda --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/ensemble_classifier.py @@ -0,0 +1,149 @@ +import os +import argparse +import collections + +import numpy as np +import torch + + +def process_files(args): + all_predictions = collections.OrderedDict() + all_labels = collections.OrderedDict() + all_uid = collections.OrderedDict() + for path in args.paths: + path = os.path.join(path, args.prediction_name) + try: + data = torch.load(path) + for dataset in data: + name, d = dataset + predictions, labels, uid = d + if name not in all_predictions: + all_predictions[name] = np.array(predictions) + if args.labels is None: + args.labels = [i for i in range(all_predictions[name].shape[1])] + if args.eval: + all_labels[name] = np.array(labels) + all_uid[name] = np.array(uid) + else: + all_predictions[name] += np.array(predictions) + assert np.allclose(all_uid[name], np.array(uid)) + except Exception as e: + print(e) + continue + return all_predictions, all_labels, all_uid + + +def get_threshold(all_predictions, all_labels, one_threshold=False): + if one_threshold: + all_predictons = {'combined': np.concatenate(list(all_predictions.values()))} + all_labels = {'combined': np.concatenate(list(all_predictions.labels()))} + out_thresh = [] + for dataset in all_predictions: + preds = all_predictions[dataset] + labels = all_labels[dataset] + out_thresh.append(calc_threshold(preds, labels)) + return out_thresh + + +def calc_threshold(p, l): + trials = [(i) * (1. / 100.) for i in range(100)] + best_acc = float('-inf') + best_thresh = 0 + for t in trials: + acc = ((apply_threshold(p, t).argmax(-1) == l).astype(float)).mean() + if acc > best_acc: + best_acc = acc + best_thresh = t + return best_thresh + + +def apply_threshold(preds, t): + assert (np.allclose(preds.sum(-1), np.ones(preds.shape[0]))) + prob = preds[:, -1] + thresholded = (prob >= t).astype(int) + preds = np.zeros_like(preds) + preds[np.arange(len(thresholded)), thresholded.reshape(-1)] = 1 + return preds + + +def threshold_predictions(all_predictions, threshold): + if len(threshold) != len(all_predictions): + threshold = [threshold[-1]] * (len(all_predictions) - len(threshold)) + for i, dataset in enumerate(all_predictions): + thresh = threshold[i] + preds = all_predictions[dataset] + all_predictions[dataset] = apply_threshold(preds, thresh) + return all_predictions + + +def postprocess_predictions(all_predictions, all_labels, args): + for d in all_predictions: + all_predictions[d] = all_predictions[d] / len(args.paths) + + if args.calc_threshold: + args.threshold = get_threshold(all_predictions, all_labels, args.one_threshold) + print('threshold', args.threshold) + + if args.threshold is not None: + all_predictions = threshold_predictions(all_predictions, args.threshold) + + return all_predictions, all_labels + + +def write_predictions(all_predictions, all_labels, all_uid, args): + all_correct = 0 + count = 0 + for dataset in all_predictions: + preds = all_predictions[dataset] + preds = np.argmax(preds, -1) + if args.eval: + correct = (preds == all_labels[dataset]).sum() + num = len(all_labels[dataset]) + accuracy = correct / num + count += num + all_correct += correct + accuracy = (preds == all_labels[dataset]).mean() + print(accuracy) + if not os.path.exists(os.path.join(args.outdir, dataset)): + os.makedirs(os.path.join(args.outdir, dataset)) + outpath = os.path.join( + args.outdir, dataset, os.path.splitext( + args.prediction_name)[0] + '.tsv') + with open(outpath, 'w') as f: + f.write('id\tlabel\n') + f.write('\n'.join(str(uid) + '\t' + str(args.labels[p]) + for uid, p in zip(all_uid[dataset], preds.tolist()))) + if args.eval: + print(all_correct / count) + + +def ensemble_predictions(args): + all_predictions, all_labels, all_uid = process_files(args) + all_predictions, all_labels = postprocess_predictions(all_predictions, all_labels, args) + write_predictions(all_predictions, all_labels, all_uid, args) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--paths', required=True, nargs='+', + help='paths to checkpoint directories used in ensemble') + parser.add_argument('--eval', action='store_true', + help='compute accuracy metrics against labels (dev set)') + parser.add_argument('--outdir', + help='directory to place ensembled predictions in') + parser.add_argument('--prediction-name', default='test_predictions.pt', + help='name of predictions in checkpoint directories') + parser.add_argument('--calc-threshold', action='store_true', + help='calculate threshold classification') + parser.add_argument('--one-threshold', action='store_true', + help='use on threshold for all subdatasets') + parser.add_argument('--threshold', nargs='+', default=None, type=float, + help='user supplied threshold for classification') + parser.add_argument('--labels', nargs='+', default=None, + help='whitespace separated list of label names') + args = parser.parse_args() + ensemble_predictions(args) + + +if __name__ == '__main__': + main() diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/eval_harness/download.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/eval_harness/download.py new file mode 100644 index 0000000000000000000000000000000000000000..27519020b1f3f4e9c2f591a2197de6f11fcf499b --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/eval_harness/download.py @@ -0,0 +1,26 @@ +# This code is originally from https://github.com/bigscience-workshop/Megatron-DeepSpeed +# under the license https://huggingface.co/spaces/bigscience/license + +# Downloads the specified taks in the evaluation harness +# This is particularly useful when running in environments where the GPU nodes +# do not have internet access. This way we can pre-download them and use the cached data-set during evaluation. + +from lm_eval import tasks +from lm_eval.tasks import ALL_TASKS +import argparse +import os + + +parser = argparse.ArgumentParser(description='Download evaluation harness', allow_abbrev=False) +parser.add_argument('--task_list', type=str, default = "all", help='Either "all" or comma separated list of tasks to download.') +args = parser.parse_args() + +def main(): + task_list = ALL_TASKS if args.task_list == 'all' else args.task_list.split(',') + tasks.get_task_dict(task_list) + +if __name__ == '__main__': + main() + + + \ No newline at end of file diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/eval_harness/evaluate.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/eval_harness/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..cd86615a2c335e2d3dd0e5f05047ec35972326c5 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/eval_harness/evaluate.py @@ -0,0 +1,436 @@ +# This code is originally from https://github.com/bigscience-workshop/Megatron-DeepSpeed +# under the license https://huggingface.co/spaces/bigscience/license + +from functools import reduce +from logging import logMultiprocessing +import os +import sys +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), + os.path.pardir,os.path.pardir))) + +from lm_eval.models.gpt2 import GPT2LM +from lm_eval import evaluator, tasks, utils +from lm_eval.base import CacheHook +from tqdm import tqdm +import torch.nn.functional as F + +from lm_eval.tasks import ALL_TASKS +from pretrain_gpt import model_provider +import numpy as np +import time + +import torch +from megatron import get_args +from megatron import print_rank_0 +from megatron import get_tokenizer +from megatron import mpu +from megatron.training import setup_model_and_optimizer, get_model +from megatron.mpu.mappings import gather_from_tensor_model_parallel_region + +from megatron.utils import get_ltor_masks_and_position_ids, unwrap_model +from megatron.p2p_communication import recv_forward, send_forward +import pickle +import json + +from torch.nn.parallel.distributed import DistributedDataParallel as torchDDP +from megatron.model.distributed import DistributedDataParallel as LocalDDP +from megatron.model.module import Float16Module +from deepspeed.runtime.pipe import schedule + +class EvalHarnessAdaptor(GPT2LM): + def __init__(self, model, tokenizer): + args = get_args() + self.args = args + self.model = model + self.tokenizer = tokenizer + self.VOCAB_SIZE = tokenizer.vocab_size + self.EOT_TOKEN_ID = tokenizer.eod + + self._max_length = args.seq_length + + # For ds we split into mini batches and then micro batches to keep pipelining api happy. + # With Megatron we just go to micro_batches directly + assert args.micro_batch_size == args.eval_micro_batch_size, \ + "EvalHarnessAdaptor (init) - Unsupported for split micro batch size" + self._batch_size = args.micro_batch_size + + self.cache_hook = CacheHook(None) + self.is_main = args.rank == 0 + self.is_local_main = args.local_rank == 0 + self._device = torch.cuda.current_device() + self.is_model_parallel = mpu.get_tensor_model_parallel_world_size() > 1 + self.is_pipe_parallel = mpu.get_pipeline_model_parallel_world_size() > 1 + self.is_data_parallel = mpu.get_data_parallel_world_size() > 1 + self.adaptive_seq_len = args.adaptive_seq_len + if self.is_data_parallel and args.moe_expert_parallel_size == 1: # For MoE model, allow a "fake data parallel" in order to partition model into multiple gpus + raise NotImplementedError("Data parallelism is currently not supported for evaluation") + + self.is_last_stage = True if not self.is_pipe_parallel else mpu.is_pipeline_last_stage() # only the last stage of the pipeline model will receive the logits + + @property + def max_length(self): + return self._max_length + + @property + def batch_size(self): + return self._batch_size + + @property + def device(self): + return self._device + + + def loglikelihood(self, requests): + new_reqs = [] + for context, continuation in requests: + if context == "": + # end of text as context + context_enc = [self.EOT_TOKEN_ID] + else: + context_enc = self.tokenizer_encode(context) + + continuation_enc = self.tokenizer_encode(continuation) + + new_reqs.append(((context, continuation), context_enc, continuation_enc)) + + return self._loglikelihood_tokens(new_reqs) + + def loglikelihood_rolling(self, requests): + # TODO: Implement caching once we've confirmed the perplexity implementation + # TODO: automatic batch size detection for vectorization + + loglikelihoods = [] + with torch.no_grad(): + for string, in tqdm(requests): + rolling_token_windows = list(map(utils.make_disjoint_window, utils.get_rolling_token_windows( + token_list=self.tokenizer_encode(string), + prefix_token=self.EOT_TOKEN_ID, + max_seq_len=self.max_length, + context_len=1, + ))) + + rolling_token_windows = [(None,) + x for x in rolling_token_windows] + + # TODO: extract out this call so it only gets called once and also somehow figure out partial caching for that + string_nll = self._loglikelihood_tokens(rolling_token_windows, disable_tqdm=True) + + # discard is_greedy + string_nll = [x[0] for x in string_nll] + + string_nll = sum(string_nll) + loglikelihoods.append(string_nll) + + return loglikelihoods + + def _loglikelihood_tokens(self, requests, disable_tqdm=False): + disable_tqdm = disable_tqdm if self.is_main else True + res = [] + res_len = 0 # storing the result length for later + self.model.eval() + with torch.no_grad(): + def _collate(x): + toks = x[1] + x[2] + return (-len(toks), tuple(toks)) + + reord = utils.Reorderer(requests, _collate) + for chunk in utils.chunks(tqdm(reord.get_reordered(), disable=disable_tqdm), self.batch_size): + inps, contlens, inplens, padding_length = [], [], [], None + for _, context_enc, continuation_enc in chunk: + # when too long to fit in context, truncate from the left + inp = torch.tensor( + (context_enc + continuation_enc)[-(self.max_length + 1):][:-1] + , dtype=torch.long).to(self.device) + inplen, = inp.shape + + cont = continuation_enc + + # since in _collate we make sure length is descending, the longest is always the first one. + padding_length = padding_length if padding_length is not None else inplen + if not self.adaptive_seq_len: + padding_length = self.max_length + # pad to length + inp = torch.cat([ + inp, # [seq] + torch.zeros(padding_length - inplen, dtype=torch.long).to(inp.device) # [padding_length - seq] + ], dim=0) + + inps.append(inp.unsqueeze(0)) + + contlens.append(cont) + inplens.append(inplen) + + logits = self._model_call(torch.cat(inps, dim=0)) + res_len += len(chunk) + if logits is not None: + multi_logits = F.log_softmax(logits, dim=-1).cpu() # [batch, seq, vocab] + + for (cache_key, _, _), logits, inp, inplen, cont_toks in zip(chunk, multi_logits, inps, inplens, contlens): + contlen = len(cont_toks) + logits = logits[inplen - contlen:inplen].unsqueeze(0) # [1, seq, vocab] + greedy_tokens = logits.argmax(dim=-1) + # cont_toks :: [1, seq] + cont_toks = torch.tensor(cont_toks, dtype=torch.long).unsqueeze(0) + max_equal = (greedy_tokens == cont_toks).all() + # last_token_slice = logits[:, -1, :].squeeze(0).tolist() + + logits = torch.gather(logits, 2, cont_toks.unsqueeze(-1)).squeeze(-1) # [1, seq] + answer = (float(logits.sum()), bool(max_equal)) + # partial caching + if cache_key is not None: + self.cache_hook.add_partial("loglikelihood", cache_key, answer) + res.append(answer) + + if not mpu.is_pipeline_last_stage(): + # @HACK: To make the eval harness happy on threads that don't have access to the results. + # We just randomly generate some data. + res = [(np.random.rand(), np.random.rand()>0.5) for _ in requests] + + return reord.get_original(res) + + def create_model_inputs(self, tokens): + args = get_args() + + attention_mask, loss_mask, position_ids = get_ltor_masks_and_position_ids( + tokens, + self.EOT_TOKEN_ID, + args.reset_position_ids, + args.reset_attention_mask, + args.eod_mask_loss) + + return (tokens, position_ids, attention_mask), (tokens, loss_mask) + + def _model_call(self, inps): + args = get_args() + + assert args.micro_batch_size == args.eval_micro_batch_size, \ + "_model_call - Unsupported for split micro batch size" + if args.deepspeed: + if args.no_pipeline_parallel: + # self.model.set_batch_fn(self.create_model_inputs) + # round up to multiple of micro_batch_size + new_size = ((len(inps) + args.micro_batch_size-1) // args.micro_batch_size) * args.micro_batch_size + padded = F.pad(inps, (0, 0, 0, new_size-len(inps)), value = 0) + # dummy data iterator for pipelining. + data_iterator = list((torch.stack(inp) for inp in utils.chunks(padded, args.micro_batch_size))) + self.model.micro_batches = len(data_iterator) + # output = self.model.eval_batch(iter(data_iterator), compute_loss = False, reduce_output = None) + output = [] + for tokens in data_iterator: + attention_mask, loss_mask, position_ids = get_ltor_masks_and_position_ids( + tokens, + self.EOT_TOKEN_ID, + args.reset_position_ids, + args.reset_attention_mask, + args.eod_mask_loss) + a_output, *other_losses = self.model(tokens, + position_ids, + attention_mask, + tokentype_ids=None, + forward_method_parallel_output=False) + output.append(a_output) + + if output is not None: + output = torch.cat(output, 0)[:len(inps)] + else: + output = None + + # hack #2 for adaptive_seq_len to work as total_loss gets appended to and shapes aren't the same + if args.adaptive_seq_len: + self.model.total_loss = None + else: + self.model.set_batch_fn(self.create_model_inputs) + # round up to multiple of micro_batch_size + new_size = ((len(inps) + args.micro_batch_size-1) // args.micro_batch_size) * args.micro_batch_size + padded = F.pad(inps, (0, 0, 0, new_size-len(inps)), value = 0) + # dummy data iterator for pipelining. + data_iterator = list((torch.stack(inp) for inp in utils.chunks(padded, args.micro_batch_size))) + self.model.micro_batches = len(data_iterator) + output = self.model.eval_batch(iter(data_iterator), compute_loss = False, reduce_output = None) + + + if output is not None: + output = torch.cat(output, 0)[:len(inps)] + else: + output = None + + # hack #2 for adaptive_seq_len to work as total_loss gets appended to and shapes aren't the same + if args.adaptive_seq_len: + self.model.total_loss = None + else: + # Since the shape of the micro-batch will change + # We need set the correct shapes here + # So that latter pipeline stages knows which shapes to expect. + # Otherwise we will deadlock. + + args.micro_batch_size = len(inps) + args.seq_length = len(inps[0]) + args.max_position_embeddings = args.seq_length + + input_tensor = recv_forward() + + # Forward pass through the model. + unwrapped_model = unwrap_model(self.model, (torchDDP, LocalDDP, Float16Module)) + unwrapped_model.set_input_tensor(input_tensor) + output = self.model(*self.create_model_inputs(inps)[0]) + send_forward(output) + + if mpu.is_pipeline_last_stage(): + return gather_from_tensor_model_parallel_region(output)[..., :self.tokenizer.vocab_size] + else: + return None + + def tokenizer_encode(self, text): + """Tokenize text *without* adding special tokens.""" + # Splitting this into its own method in case we need to handle special cases for different tokenizers + from megatron.tokenizer.gpt2_tokenization import GPT2Tokenizer + if isinstance(self.tokenizer.tokenizer, GPT2Tokenizer): + return self.tokenizer.tokenizer.encode(text) + else: + return self.tokenizer.tokenizer.encode(text, add_special_tokens=False) + + +from megatron.initialize import initialize_megatron +import megatron + +from tools.convert_checkpoint.deepspeed_checkpoint import DeepSpeedCheckpoint +from tools.convert_checkpoint.deepspeed_to_megatron import _create_rank_checkpoint + +def override_args(args, override_args, skip_keys, skip_if_specified_keys): + for k, v in vars(override_args).items(): + if k in skip_keys: + continue + if k in skip_if_specified_keys and getattr(args, k) is not None: + continue + setattr(args, k, v) + + +# Note(Hesslow): +# The model loading is a bit convoluted. +# We want to parse out the model arguments from the checkpoint and use those to initialize megatron-ds. +# +# However megatron-ds expects its arguments on the command line. +# And at that point we don't know them. +# +# Instead we use Jasons way: we load the arguments form the checkpoint and then override _parse_args to return whatever args we want. +# +# If the checkpoint is old, some new arguments may have been introduced and the code will expect these arguments to exist. +# In order to support this we _first_ parse the arguments normally, and then override them with the arguments from the checkpoint. +# Keeping the default-value of newer arguments. +# +# We then use the megatron deepspeed converter to load the deepspeed checkpoints as if they we're megatron checkpoints. +def load_ds_checkpoint_and_setup_megatron(extra_args_provider): + # parse the megatorn args. But wait with initalizing megatron. + # avoid printing the arguments, since they will later be overridden. + _print_args = megatron.arguments._print_args + megatron.arguments._print_args = lambda *_args, **kwarg: None + args = _parse_args(extra_args_provider) + + ds_checkpoint = DeepSpeedCheckpoint(args.load, + tp_degree=args.tensor_model_parallel_size, + pp_degree=args.pipeline_model_parallel_size, + no_pp=args.no_pipeline_parallel) + + + cp_args = ds_checkpoint.get_args() + # Merge the current args with the checkpoint args. + skip_keys = ['world_size', 'rank', 'local_rank','device_count', 'micro_batch_size','global_batch_size', 'batch_size', 'tensorboard_dir', 'deepspeed', 'deepspeed_config', + 'data_parallel_size', 'pipeline_model_parallel_size', 'tensor_model_parallel_size', 'moe_expert_parallel_size', 'moe_token_dropping', 'load', 'rampup_batch_size', 'iteration', 'inference'] + + skip_if_specified = ['merge_file', 'vocab_file'] + + if args.eval_fp32: + cp_args.fp16 = False + cp_args.bf16 = False + cp_args.params_dtype = torch.float32 + + override_args(args, cp_args, skip_keys, skip_if_specified) + + # stop megatron from reparsing the arguments. + megatron.global_vars._parse_args = lambda *_args, **kwarg: args + megatron.global_vars._GLOBAL_ARGS = args + + initialize_megatron() + torch.distributed.barrier() + + # Initializing megatron will update eg. tokenizer size. Override again. + override_args(args, cp_args, skip_keys, skip_if_specified) + + # print final arguments. + _print_args(args) + if args.deepspeed: + + # Hack #3: + # Loading pipelined models in deepspeed with different TP than it was originally trained on fails + # due to a sanity check, that makes sure that all state_dicts that we merge contains attention layers. + # This, however, is not true for pipelining when we will merge the state_dict for the embeddings which + # which does not contain these attention-specific keys. + # + # Deepspeed does however manage to load the model if we just turn off this sanity check. + import deepspeed + deepspeed.runtime.state_dict_factory.MegatronSDLoader.sanity_check = lambda self, ckpt_file_name: None + + + cp_path = args.load + args.load = None + model, _, _ = setup_model_and_optimizer(model_provider) + model = model[0] + zero_enabled = model._config.zero_enabled + model._config.zero_enabled = False + _, _ = model.load_checkpoint(cp_path, tag = '.', load_optimizer_states=False, load_lr_scheduler_states=False, load_module_only=True) + model._config.zero_enabled = zero_enabled + else: + model = get_model(model_provider)[0] + # Initialize megatron model using the parsed state dict. + sd = _create_rank_checkpoint(ds_checkpoint, None, mpu.get_tensor_model_parallel_rank(), mpu.get_pipeline_model_parallel_rank(), True) + + model.load_state_dict(sd['model'], strict=True) + + if args.eval_fp32: + model = model.float() + + torch.distributed.barrier() + return model + +def tasks_args(parser): + """Provide extra arguments required for tasks.""" + group = parser.add_argument_group(title='Evaluation options') + group.add_argument('--task_list', type=str, default = "all", help='Either "all" or comma separated list of tasks.') + group.add_argument('--results_path', type=str, default = "./results.json", help='Path to where the results will be stored.') + group.add_argument('--adaptive_seq_len', default = False, action='store_true', + help='Should the sequence length be adapted to the batch during evaluation, if in fp16 the results will be slightly different due to numerical errors but greatly speed up evaluation.') + group.add_argument('--eval_fp32', default = False, action='store_true', help='Should the evaluation run in fp32') + return parser + +from megatron.global_vars import _parse_args + +def main(): + start = time.time() + model = load_ds_checkpoint_and_setup_megatron(extra_args_provider=tasks_args) + + args = get_args() + if args.deepspeed and args.adaptive_seq_len: + # adaptive_seq_len hack #1: + # CL automatically enables reset_activation_shape() which allows us to change input shapes + # and it also reshapes the attenion scores in attention_mask_func + args.curriculum_learning = 1 + + task_list = ALL_TASKS if args.task_list == 'all' else args.task_list.split(',') + task_dict = tasks.get_task_dict(task_list) + + model.module.activation_checkpoint_interval = 0 + model._compute_loss = False + model.fwd_outputs = [] + + tokenizer = get_tokenizer() + adaptor = EvalHarnessAdaptor(model, tokenizer) + results = evaluator.evaluate(adaptor, task_dict, False, 0, None) + + if mpu.is_pipeline_last_stage() and mpu.get_tensor_model_parallel_rank() == 0: + print(json.dumps(results, indent=2)) + with open(args.results_path, 'w') as outfile: + json.dump(results, outfile, indent = 4) + end = time.time() + print("evaluation of {} ends in {:.2f} sec, or {:.2f} min, or {:.2f} hr".format(args.task_list, end-start, (end-start)/60.0, (end-start)/3600.0)) + +if __name__ == '__main__': + main() diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/eval_utils.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/eval_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..600abd6eb47546396373e5f9ab6e5b00750c1eaa --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/eval_utils.py @@ -0,0 +1,202 @@ +# coding=utf-8 +# Copyright (c) 2023 Habana Labs, Ltd. an Intel Company. +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed 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. + +"""Evaluation utilities.""" + +import os +import time +from functools import partial + +import torch + +from megatron import get_args +from megatron import print_rank_last, is_last_rank +from megatron import mpu +from megatron.schedules import get_forward_backward_func +from tasks.finetune_utils import build_data_loader +from tasks.finetune_utils import process_batch + + +def accuracy_func_provider(single_dataset_provider): + """Provide function that calculates accuracies.""" + args = get_args() + + # Build dataloaders. + datapaths = args.valid_data + dataloaders = [] + for datapath in datapaths: + dataset = single_dataset_provider(datapath) + dataloader = build_data_loader( + dataset, args.orig_micro_batch_size, num_workers=args.num_workers, + drop_last=(mpu.get_data_parallel_world_size() > 1)) + dataloaders.append((dataset.dataset_name, dataloader)) + + def metrics_func(model, epoch, output_predictions=False): + print_rank_last('calculating metrics ...') + correct = 0 + total = 0 + if output_predictions: + assert mpu.get_data_parallel_world_size() == 1 + named_predictions = [] + names = 'predictions' + for name, dataloader in dataloaders: + output = calculate_correct_answers(name, model, dataloader, + epoch, output_predictions) + if not output_predictions: + correct_ans, total_count = output + else: + correct_ans, total_count, predictions = output + named_predictions.append((name, predictions)) + names += '_' + name + correct += correct_ans + total += total_count + if is_last_rank(): + percent = float(correct) * 100.0 / float(total) + print(' >> |epoch: {}| overall: correct / total = {} / {} = ' + '{:.4f} %'.format(epoch, correct, total, percent)) + + if output_predictions and is_last_rank(): + assert args.load is not None + filename = os.path.join(args.load, names + '.pt') + torch.save(named_predictions, filename) + + return metrics_func + + +def calculate_correct_answers(name, model, dataloader, + epoch, output_predictions): + """Calculate correct over total answers and return prediction if the + `output_predictions` is true.""" + args = get_args() + forward_backward_func = get_forward_backward_func() + start_time = time.time() + for m in model: + m.eval() + assert args.micro_batch_size == args.eval_micro_batch_size, \ + "calculate_correct_answers - Unsupported for split micro batch size" + saved_micro_batch_size = args.micro_batch_size + saved_global_batch_size = args.global_batch_size + + ds = dataloader.dataset + if hasattr(ds, 'sample_multiplier'): + # If our dataset as a sample_multiplier attribute that means + # each "sample" from the dataset actually has multiple samples + # that will collapse into the batch dimension (for example in + # the RACE dataset that has several options), we need to + # account for that when setting the micro batch size. + sample_multiplier = ds.sample_multiplier + else: + sample_multiplier = 1 + micro_batch_size_times_data_parallel = args.orig_micro_batch_size * args.data_parallel_size + num_micro_batches = args.orig_global_batch_size // micro_batch_size_times_data_parallel + + def loss_func(output_predictions, labels, output_tensor): + logits = output_tensor + + loss_dict = {} + # Add output predictions. + if output_predictions: + assert False + loss_dict['softmaxes'] = torch.nn.Softmax(dim=-1)( + logits.float()).data.cpu().numpy().tolist() + loss_dict['labels'] = labels.data.cpu().numpy().tolist() + loss_dict['ids'] = batch['uid'].cpu().numpy().tolist() + # Compute the correct answers. + predicted = torch.argmax(logits, dim=-1) + corrects = (predicted == labels) + # Add to the counters. + loss_dict['total'] = labels.size(0) + loss_dict['correct'] = corrects.sum().item() + + return 0, loss_dict + + # defined inside to capture output_predictions + def correct_answers_forward_step(batch, model): + try: + batch_ = next(batch) + except BaseException: + batch_ = batch + tokens, types, labels, attention_mask = process_batch(batch_) + + # Forward model. + args = get_args() + output_tensor = model(tokens, attention_mask, tokentype_ids=types) + + return output_tensor, partial(loss_func, output_predictions, labels) + + with torch.no_grad(): + # For all the batches in the dataset. + total = 0 + correct = 0 + if output_predictions: + # This option is only possible when data parallel size is 1. + assert mpu.get_data_parallel_world_size() == 1 + softmaxes = [] + labels = [] + ids = [] + for _, batch in enumerate(dataloader): + # For evaluation only mode we use drop_last = False to get all the + # samples, which means we might not have a full batch, so we + # adjust batch_size here to actual batch size of data + actual_batch_size = len(batch['label']) + # ... applying sample_multiplier if necessary + args.micro_batch_size = actual_batch_size * sample_multiplier + # Next line should be considered once eval_micro_batch_size is supported here + args.eval_micro_batch_size = args.micro_batch_size + args.global_batch_size = actual_batch_size * sample_multiplier * num_micro_batches + + loss_dicts = forward_backward_func(correct_answers_forward_step, batch, model, + optimizer=None, timers=None, forward_only=True) + + for loss_dict in loss_dicts: + if output_predictions: + softmaxes.extend(loss_dict['softmaxes']) + labels.extend(loss_dict['labels']) + ids.extend(loss_dict['ids']) + total += loss_dict['total'] + correct += loss_dict['correct'] + + + for m in model: + m.train() + args.micro_batch_size = saved_micro_batch_size + # Next line should be considered once eval_micro_batch_size is supported here + args.eval_micro_batch_size = args.micro_batch_size + args.global_batch_size = saved_global_batch_size + + # Reduce. + if mpu.is_pipeline_last_stage(): + unreduced = torch.cuda.LongTensor([correct, total]) + torch.distributed.all_reduce(unreduced, + group=mpu.get_data_parallel_group()) + + # Print on screen. + + correct_ans = unreduced[0].item() + total_count = unreduced[1].item() + percent = float(correct_ans) * 100.0 / float(total_count) + elapsed_time = time.time() - start_time + print_rank_last(' > |epoch: {}| metrics for {}: correct / total ' + '= {} / {} = {:.4f} %, elapsed time (sec): {:.3f}'.format( + epoch, name, correct_ans, total_count, + percent, elapsed_time)) + + if output_predictions: + return correct_ans, total_count, (softmaxes, labels, ids) + return correct_ans, total_count + if output_predictions: + return 0, 0, () + return 0, 0 diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/finetune_utils.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/finetune_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..af167eeb8feb8e856969ce7cf15a0da95f4053dc --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/finetune_utils.py @@ -0,0 +1,296 @@ +# coding=utf-8 +# Copyright (c) 2023 Habana Labs, Ltd. an Intel Company. +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed 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. + +"""Finetune utilities.""" + +from functools import partial + +import torch + +from megatron import get_args +from megatron import print_rank_0 +from megatron import get_timers +from megatron import mpu +from megatron.checkpointing import load_checkpoint +from megatron.checkpointing import save_checkpoint +from megatron.training import evaluate_and_print_results +from megatron.training import setup_model_and_optimizer +from megatron.training import train_step +from megatron.training import training_log +from megatron.utils import average_losses_across_data_parallel_group +from megatron.utils import calc_params_l2_norm +from megatron.utils import check_adlr_autoresume_termination + + +def process_batch(batch): + """Process batch and produce inputs for the model.""" + args = get_args() + + tokens = batch['text'].long().cuda().contiguous() + types = batch['types'].long().cuda().contiguous() + labels = batch['label'].long().cuda().contiguous() + attention_mask = batch['padding_mask'].float().cuda().contiguous() + if args.fp16: + attention_mask = attention_mask.half() + + return tokens, types, labels, attention_mask + + +def cross_entropy_loss_func(labels, output_tensor): + logits = output_tensor + + # Cross-entropy loss. + loss_func = torch.nn.CrossEntropyLoss() + loss = loss_func(logits.contiguous().float(), labels) + + # Reduce loss for logging. + averaged_loss = average_losses_across_data_parallel_group([loss]) + + return loss, {'lm loss': averaged_loss[0]} + + +def _cross_entropy_forward_step(batch, model): + """Simple forward step with cross-entropy loss.""" + timers = get_timers() + + # Get the batch. + timers('batch-generator').start() + try: + batch_ = next(batch) + except BaseException: + batch_ = batch + tokens, types, labels, attention_mask = process_batch(batch_) + timers('batch-generator').stop() + + # Forward model. + output_tensor = model(tokens, attention_mask, tokentype_ids=types) + + return output_tensor, partial(cross_entropy_loss_func, labels) + + +def build_data_loader(dataset, micro_batch_size, num_workers, drop_last): + """Data loader. Note that batch-size is the local (per GPU) batch-size.""" + + # Sampler. + world_size = mpu.get_data_parallel_world_size() + rank = mpu.get_data_parallel_rank() + sampler = torch.utils.data.distributed.DistributedSampler( + dataset, num_replicas=world_size, rank=rank) + + # Data loader. Note that batch size is the per GPU batch size. + data_loader = torch.utils.data.DataLoader(dataset, + batch_size=micro_batch_size, + sampler=sampler, + shuffle=False, + num_workers=num_workers, + drop_last=drop_last, + pin_memory=True) + + return data_loader + + +def _build_infinite_size_dataloader(dataloader): + """Build a looped dataloader with infinite size.""" + + iterator = dataloader.__iter__() + while True: + try: + yield iterator.__next__() + except StopIteration: + iterator = dataloader.__iter__() + + +def _build_train_valid_dataloaders(train_dataset, valid_dataset): + """Traing and validation dataloaders.""" + args = get_args() + + assert args.micro_batch_size == args.eval_micro_batch_size, \ + "_build_train_valid_dataloaders - Unsupported for split micro batch size" + print_rank_0('building train and validation dataloaders ...') + # Training dataset. + train_dataloader = build_data_loader(train_dataset, args.micro_batch_size, + args.num_workers, not args.keep_last) + # Set the training iterations. + args.train_iters_per_epoch = len(train_dataloader) + args.train_iters = args.epochs * args.train_iters_per_epoch + # Validation dataset. For this dataset, we do not need to set up + # shuffling so we can just use a simple infinite loop. + valid_dataloader_ = build_data_loader(valid_dataset, args.micro_batch_size, + args.num_workers, not args.keep_last) + valid_dataloader = _build_infinite_size_dataloader(valid_dataloader_) + + # Now that we've built the data loaders, set batch_size arguments + # to the actual batch size the model will see for this dataset. + # This is necessary so pipeline transfers know what size they are + # and the LR schedule, which is based on samples seen, gets set + # correctly. + args.orig_micro_batch_size = args.micro_batch_size + args.orig_global_batch_size = args.global_batch_size + if hasattr(train_dataset, 'sample_multiplier'): + # If our dataset as a sample_multiplier attribute that means + # each "sample" from the dataset actually has multiple samples + # that will collapse into the batch dimension (for example in + # the RACE dataset that has several options), we need to + # account for that when setting the micro batch size. + args.micro_batch_size *= train_dataset.sample_multiplier + args.global_batch_size *= train_dataset.sample_multiplier + + return train_dataloader, valid_dataloader + + +def _train(model, optimizer, lr_scheduler, forward_step, + train_dataloader, valid_dataloader, end_of_epoch_callback): + """Train the model.""" + args = get_args() + timers = get_timers() + + # Turn on training mode which enables dropout. + for m in model: + m.train() + + # Tracking loss. + losses_dict_sum = {} + + # Starting epoch and iteration + start_epoch = args.iteration // args.train_iters_per_epoch + start_iteration = args.iteration % args.train_iters_per_epoch + iteration = args.iteration + + # Memory reporting flag. + report_memory_flag = True + + # For each remaining epoch + timers('interval-time').start() + for epoch in range(start_epoch, args.epochs): + print_rank_0('working on epoch {} ...'.format(epoch + 1)) + + # Set the data loader epoch to shuffle the index iterator. + train_dataloader.sampler.set_epoch(args.seed + epoch) + + # For all the batches in the dataset. + for iteration_, batch in enumerate(train_dataloader): + + # Ignore the iterations before starting value + if iteration_ < start_iteration: + continue + # Set to zero so the next epoch does not skip any batches. + start_iteration = 0 + + # Train for one step. + out = train_step(forward_step, batch, model, optimizer, lr_scheduler) + losses_dict, skipped_iter, grad_norm, num_zeros_in_grad = out + iteration += 1 + + # Logging. + params_norm = None + if args.log_params_norm: + params_norm = calc_params_l2_norm(model) + report_memory_flag = training_log(losses_dict, losses_dict_sum, + optimizer.param_groups[0]['lr'], + iteration, + optimizer.get_loss_scale().item(), + report_memory_flag, skipped_iter, + grad_norm, params_norm, num_zeros_in_grad) + + # Autoresume + if args.adlr_autoresume and \ + (iteration % args.adlr_autoresume_interval == 0): + check_adlr_autoresume_termination(iteration, model, + optimizer, lr_scheduler) + + # Checkpointing + if args.save and args.save_interval and \ + iteration % args.save_interval == 0: + save_checkpoint(iteration, model, optimizer, lr_scheduler) + + # Evaluation + if args.eval_interval and iteration % args.eval_interval == 0: + prefix = 'iteration {}'.format(iteration) + evaluate_and_print_results(prefix, forward_step, + valid_dataloader, model, + iteration, False) + + # Checkpointing at the end of each epoch. + if args.save: + save_checkpoint(iteration, model, optimizer, lr_scheduler) + + # Callback at the end of each epoch. + if end_of_epoch_callback is not None: + end_of_epoch_callback(model, epoch) + + +def finetune(train_valid_datasets_provider, model_provider, + forward_step=_cross_entropy_forward_step, + end_of_epoch_callback_provider=None): + """Main finetune function used across all tasks.""" + args = get_args() + timers = get_timers() + + assert args.rampup_batch_size is None, \ + 'batch size scaling is not supported for finetuning' + + # Train and validation data loaders. + timers('train/valid/test dataset/dataloder').start() + if args.epochs > 0: + train_dataset, valid_dataset = train_valid_datasets_provider() + train_dataloader, valid_dataloader = _build_train_valid_dataloaders( + train_dataset, valid_dataset) + else: + args.train_iters = 0 + timers('train/valid/test dataset/dataloder').stop() + + # Build calback function. + timers('callback function').start() + end_of_epoch_callback = None + if end_of_epoch_callback_provider is not None: + end_of_epoch_callback = end_of_epoch_callback_provider() + timers('callback function').stop() + + # Build model, optimizer and learning rate scheduler. + timers('model and optimizer').start() + model, optimizer, lr_scheduler = setup_model_and_optimizer(model_provider) + timers('model and optimizer').stop() + + # If pretrained checkpoint is provided and we have not trained for + # any iteration (i.e., iteration is zero), then load the pretrained + # checkpoint. + timers('pretrained checkpoint').start() + if args.iteration == 0 and args.pretrained_checkpoint is not None: + original_load = args.load + args.load = args.pretrained_checkpoint + _ = load_checkpoint(model, None, None) + args.load = original_load + # This is critical when only model is loaded. We should make sure + # main parameters are also updated. + optimizer.reload_model_params() + timers('pretrained checkpoint').stop() + + # Print setup timing. + print_rank_0('done with setups ...') + timers.log(['train/valid/test dataset/dataloder', 'callback function', + 'model and optimizer', 'pretrained checkpoint']) + print_rank_0('training ...') + + # Finetune the model. + if args.epochs > 0: + _train(model, optimizer, lr_scheduler, forward_step, + train_dataloader, valid_dataloader, end_of_epoch_callback) + # Or just evaluate. + else: + if end_of_epoch_callback is not None: + print_rank_0('evaluation only mode, setting epoch to -1') + end_of_epoch_callback(model, epoch=-1, output_predictions=True) + print_rank_0('done :-)') diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/glue/mnli.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/glue/mnli.py new file mode 100644 index 0000000000000000000000000000000000000000..547a2a0052e92d184d155f13b6576c43eee4546d --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/glue/mnli.py @@ -0,0 +1,84 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed 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. + +"""MNLI dataset.""" + +from megatron import print_rank_0 +from tasks.data_utils import clean_text +from .data import GLUEAbstractDataset + + +LABELS = {'contradiction': 0, 'entailment': 1, 'neutral': 2} + + +class MNLIDataset(GLUEAbstractDataset): + + def __init__(self, name, datapaths, tokenizer, max_seq_length, + test_label='contradiction'): + self.test_label = test_label + super().__init__('MNLI', name, datapaths, + tokenizer, max_seq_length) + + def process_samples_from_single_path(self, filename): + """"Implement abstract method.""" + print_rank_0(' > Processing {} ...'.format(filename)) + + samples = [] + total = 0 + first = True + is_test = False + with open(filename, 'r') as f: + for line in f: + row = line.strip().split('\t') + if first: + first = False + if len(row) == 10: + is_test = True + print_rank_0( + ' reading {}, {} and {} columns and setting ' + 'labels to {}'.format( + row[0].strip(), row[8].strip(), + row[9].strip(), self.test_label)) + else: + print_rank_0(' reading {} , {}, {}, and {} columns ' + '...'.format( + row[0].strip(), row[8].strip(), + row[9].strip(), row[-1].strip())) + continue + + text_a = clean_text(row[8].strip()) + text_b = clean_text(row[9].strip()) + unique_id = int(row[0].strip()) + label = row[-1].strip() + if is_test: + label = self.test_label + + assert len(text_a) > 0 + assert len(text_b) > 0 + assert label in LABELS + assert unique_id >= 0 + + sample = {'text_a': text_a, + 'text_b': text_b, + 'label': LABELS[label], + 'uid': unique_id} + total += 1 + samples.append(sample) + + if total % 50000 == 0: + print_rank_0(' > processed {} so far ...'.format(total)) + + print_rank_0(' >> processed {} samples.'.format(len(samples))) + return samples diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/main.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/main.py new file mode 100644 index 0000000000000000000000000000000000000000..baf1c064bf9c26c322c5ebf5e94143649c869fa3 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/main.py @@ -0,0 +1,50 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed 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. + +"""Main tasks functionality.""" + +import os +import sys +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), + os.path.pardir))) + +from tasks.tasks_args import get_tasks_args +from megatron import get_args +from megatron.initialize import initialize_megatron + + +if __name__ == '__main__': + + initialize_megatron(extra_args_provider=get_tasks_args) + + args = get_args() + + if args.num_layers_per_virtual_pipeline_stage is not None: + print("Interleaved pipeline schedule is not yet supported for downstream tasks.") + exit() + + if args.task == 'RACE': + from race.finetune import main + elif args.task in ['MNLI', 'QQP']: + from glue.finetune import main + elif args.task in ['LAMBADA', 'WIKITEXT103']: + from zeroshot_gpt.evaluate import main + elif args.task in ['ICT-ZEROSHOT-NQ']: + from orqa.evaluate_orqa import main + else: + raise NotImplementedError('Task {} is not implemented.'.format( + args.task)) + + main() diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/main_3d.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/main_3d.py new file mode 100644 index 0000000000000000000000000000000000000000..4d989923a049ae2db5996860cd8c13412e02746b --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/main_3d.py @@ -0,0 +1,114 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed 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. + +"""Main 3D parallel tasks functionality.""" + +import os +import sys +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) + +import torch +import megatron +from deepspeed.checkpoint.deepspeed_checkpoint import DeepSpeedCheckpoint +from tasks.tasks_args import get_tasks_args +from megatron.global_vars import _parse_args +from megatron import get_args +from megatron.initialize import initialize_megatron + + +def override_args(base_args, override, skip_keys, skip_if_specified_keys): + for k, v in vars(override).items(): + if k in skip_keys: + continue + if k in skip_if_specified_keys and getattr(base_args, k) is not None: + continue + setattr(base_args, k, v) + + +# Below function is adapted from tasks/eval_harness/evaluate.py +def init_args(extra_args_provider): + # parse the megatorn args. But wait with initializing megatron. + # avoid printing the arguments, since they will later be overridden. + _print_args = megatron.arguments._print_args + megatron.arguments._print_args = lambda *_args, **kwarg: None + args = _parse_args(extra_args_provider) + + ds_checkpoint = DeepSpeedCheckpoint(args.load, + tp_degree=args.tensor_model_parallel_size, + pp_degree=args.pipeline_model_parallel_size, + dp_degree=args.data_parallel_size) + + # Merge the current args with the checkpoint args. + cp_args = ds_checkpoint.get_args() + skip_keys = ['world_size', 'rank', 'local_rank','device_count', 'micro_batch_size','global_batch_size', + 'batch_size', 'tensorboard_dir', 'deepspeed', 'deepspeed_config', 'deepspeed_configuration', + 'data_parallel_size', 'pipeline_model_parallel_size', 'tensor_model_parallel_size', + 'moe_expert_parallel_size', 'moe_token_dropping', 'load', 'rampup_batch_size', 'iteration', + 'inference', 'bias_dropout_fusion', 'masked_softmax_fusion', 'bias_dropout_fusion', + 'fp16', 'bf16', 'use_seq_len_plus_one_tokens', 'log_interval', + 'seq_length', 'max_position_embeddings', 'encoder_seq_length', + 'distributed_backend', 'use_hpu', 'device', 'selective_recompute_mark_step', + 'checkpoint_activations', 'checkpoint_activations_granularity', 'deepspeed_activation_checkpointing'] + + if args.checkpoint_override_tokenizer: + skip_keys += ['merge_file', 'tokenizer_eod_id', 'tokenizer_model_file', 'tokenizer_type', + 'vocab_extra_ids', 'vocab_file'] + + skip_if_specified = ['merge_file', 'vocab_file'] + + override_args(args, cp_args, skip_keys, skip_if_specified) + + # stop megatron from reparsing the arguments. + megatron.global_vars._parse_args = lambda *_args, **kwarg: args + megatron.global_vars._GLOBAL_ARGS = args + + initialize_megatron() + torch.distributed.barrier() + + # Initializing megatron will update eg. tokenizer size. Override again. + override_args(args, cp_args, skip_keys, skip_if_specified) + + # Create minimal deepspeed configuration + if args.deepspeed_config is None: + args.deepspeed_configuration = { + 'train_batch_size': args.global_batch_size, + 'train_micro_batch_size_per_gpu': args.micro_batch_size, + 'bf16': {'enabled': args.bf16}, + 'fp16': {'enabled': args.fp16}, + 'zero_optimization': {'stage': 0}, + } + + # print final arguments. + _print_args(args) + + +if __name__ == '__main__': + + def my_rebuild(data, dtype, device, requires_grad): + device = 'cpu' if 'hpu' in device else device + tensor = torch.from_numpy(data).to(dtype=dtype, device=device) + tensor.requires_grad = requires_grad + return tensor + + torch._utils._rebuild_device_tensor_from_numpy = my_rebuild + init_args(get_tasks_args) + args = get_args() + + if args.task in ['LAMBADA', 'WIKITEXT103']: + from zeroshot_gpt.evaluate import main + else: + raise NotImplementedError('Task {} is not implemented.'.format(args.task)) + + main() diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/orqa/evaluate_orqa.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/orqa/evaluate_orqa.py new file mode 100644 index 0000000000000000000000000000000000000000..7e6b269231a5a066a7ab8d2dfae37393c2f4bd1d --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/orqa/evaluate_orqa.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed 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. + +"""Main tasks functionality.""" + +import os +import sys + +from megatron import get_args +from tasks.orqa.evaluate_utils import ORQAEvaluator + +def main(): + """ + Main program + """ + + args = get_args() + + # Set up the model and evaluator + evaluator = ORQAEvaluator() + + # Run evaluation + if args.qa_data_dev is not None: + evaluator.evaluate(args.qa_data_dev, "DEV") + + if args.qa_data_test is not None: + evaluator.evaluate(args.qa_data_test, "TEST") + diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/orqa/evaluate_utils.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/orqa/evaluate_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ebee03522e1df560b34d0a49cc75cb7128a6e472 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/orqa/evaluate_utils.py @@ -0,0 +1,188 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed 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 torch + +from megatron import get_args, print_rank_0 +from megatron.checkpointing import load_biencoder_checkpoint +from megatron.data.orqa_wiki_dataset import get_open_retrieval_wiki_dataset +from tasks.orqa.natural_questions.nq import get_nq_dataset +from tasks.orqa.natural_questions.nq import get_one_epoch_nq_dataloader +from tasks.orqa.natural_questions.nq import process_nq_batch +from tasks.orqa.natural_questions.qa_utils import calculate_matches +from megatron.data.realm_index import OpenRetreivalDataStore, FaissMIPSIndex +from megatron.model.biencoder_model import biencoder_model_provider +from megatron.training import get_model + +class ORQAEvaluator(object): + def __init__(self): + args = get_args() + self.embedding_size = args.hidden_size + self.faiss_use_gpu = args.faiss_use_gpu + self.evidence_embedder_obj = None + self.evidence_dataset = None + self.mips_index = None + self.eval_dataset = None + + # Get Evidence (Wikipedia) dataset + self.get_evidence_dataset() + + # Load query encoder checkpoint + only_query_model = True + if args.biencoder_shared_query_context_model: + only_query_model = False + + model = get_model(lambda: biencoder_model_provider(only_query_model=\ + only_query_model, biencoder_shared_query_context_model=\ + args.biencoder_shared_query_context_model)) + + self.model = load_biencoder_checkpoint(model, + only_query_model=only_query_model) + + assert len(self.model) == 1 + self.model[0].eval() + + # Load faiss indexer + self.faiss_wrapper() + + def get_evidence_embedding(self): + # This will load the embedding from the embedding path + self.evidence_embedder_obj = OpenRetreivalDataStore(load_from_path=True) + + def get_evidence_dataset(self): + self.evidence_dataset = get_open_retrieval_wiki_dataset() + + def faiss_wrapper(self): + # Initialize FAISS wrapper on local rank = 0 as the evidence embeddings + # is distributed over all the GPUs in a node and FAISS is not + # thread-safe + args = get_args() + if args.local_rank == 0: + # Get evidence embeddings computed using context encoder + self.get_evidence_embedding() + + assert self.evidence_embedder_obj is not None + self.mips_index = FaissMIPSIndex(embed_size=self.embedding_size, + embed_data=self.evidence_embedder_obj, + use_gpu=self.faiss_use_gpu) + + # Wait for the FAISS index to be initialized in all the nodes + torch.distributed.barrier() + + def generate_query_vectors(self, qa_data, split): + + self.eval_dataset = get_nq_dataset(qa_data, split) + dataloader = get_one_epoch_nq_dataloader(self.eval_dataset) + + query_vectors = [] + reference_list = [] + + for batch in dataloader: + # batch also has query_tokens and query_pad_data + query_tokens, query_mask, query_types, \ + query_len, reference = process_nq_batch(batch) + + assert len(self.model) == 1 + unwrapped_model = self.model[0] + while not hasattr(unwrapped_model, 'embed_text'): + unwrapped_model = unwrapped_model.module + + with torch.no_grad(): + query_logits = unwrapped_model.embed_text( + unwrapped_model.query_model, query_tokens, + query_mask, query_types) + + reference_list.extend(reference) + query_vectors.extend(query_logits.split(1, dim=0)) + if len(query_vectors) % 100 == 0: + print_rank_0('Encoded queries {}'.format(len(query_vectors))) + + query_tensor = torch.cat(query_vectors, dim=0) + print_rank_0('Total encoded queries tensor {}'.format(query_tensor.size())) + + assert query_tensor.size(0) == len(self.eval_dataset) + return query_tensor, reference_list + + def evaluate(self, qa_data, split): + args = get_args() + query_tensor, reference_list = self.generate_query_vectors(qa_data, \ + split) + local_rank = args.local_rank + rank = torch.distributed.get_rank() + device_count = torch.cuda.device_count() + num_nodes = torch.distributed.get_world_size() // device_count + node_id = rank // device_count + + for node in range(num_nodes): + start_rank = node * device_count + end_rank = (node + 1) * device_count + ranks_list = list(range(start_rank, end_rank)) + node_group = torch.distributed.new_group(ranks=ranks_list) + + if node_id == node: + device_start_rank = start_rank + group = node_group + + input_ = torch.empty_like(query_tensor).copy_(query_tensor).detach_() + tensor_list = [torch.empty_like(input_) for _ in range(device_count)] + torch.distributed.all_gather(tensor_list, query_tensor, group=group) + + if local_rank == 0 and self.mips_index is not None: + all_query_tensor = torch.cat(tensor_list, dim=0).contiguous() + + distance, topkindex = self.mips_index.search_mips_index( + all_query_tensor, top_k=args.faiss_topk_retrievals, + reconstruct=False) + distance = torch.from_numpy(distance).cuda() + topkindex = torch.LongTensor(topkindex).cuda() + + if local_rank != 0: + distance = torch.empty(device_count * len(query_tensor), \ + args.faiss_topk_retrievals, dtype=torch.float32).cuda() + topkindex = torch.empty(device_count * len(query_tensor), \ + args.faiss_topk_retrievals, dtype=torch.int64).cuda() + + torch.distributed.broadcast(distance, src=device_start_rank, \ + group=group) + torch.distributed.broadcast(topkindex, src=device_start_rank, \ + group=group) + + distance = torch.split(distance, len(query_tensor), dim=0)\ + [local_rank] + topkindex = torch.split(topkindex, len(query_tensor), dim=0)\ + [local_rank] + + top_ids_and_scores = [] + for darray, topkarray in zip(distance, topkindex): + top_ids_and_scores.append((topkarray.tolist(), darray.tolist())) + + passages = self.evidence_dataset.id2text + match_stats = calculate_matches(passages, + reference_list, + top_ids_and_scores, + workers_num=args.num_workers, + match_type=args.faiss_match) + top_k_hits = match_stats.top_k_hits + + print_rank_0("{} SET RESULTS".format(split)) + print_rank_0("topk-{} documents hits {}".format( + args.faiss_topk_retrievals, top_k_hits)) + top_k_hits = [v / len(top_ids_and_scores) for v in top_k_hits] + print_rank_0("top-k documents hits accuracy {}".format(top_k_hits)) + + for i in args.retriever_report_topk_accuracies: + print_rank_0("top-{}: {:.2f}".format(i, top_k_hits[i-1] * 100)) + + return diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/race/data.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/race/data.py new file mode 100644 index 0000000000000000000000000000000000000000..c4967a0842fc35b6cbfa20dff49a3dc93342f073 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/race/data.py @@ -0,0 +1,135 @@ + +import glob +import json +import os +import time + +from torch.utils.data import Dataset + +from megatron import print_rank_0 +from tasks.data_utils import build_sample +from tasks.data_utils import build_tokens_types_paddings_from_ids +from tasks.data_utils import clean_text + + +NUM_CHOICES = 4 +MAX_QA_LENGTH = 128 + + +class RaceDataset(Dataset): + + def __init__(self, dataset_name, datapaths, tokenizer, max_seq_length, + max_qa_length=MAX_QA_LENGTH): + + self.dataset_name = dataset_name + print_rank_0(' > building RACE dataset for {}:'.format( + self.dataset_name)) + + string = ' > paths:' + for path in datapaths: + string += ' ' + path + print_rank_0(string) + + self.samples = [] + for datapath in datapaths: + self.samples.extend(process_single_datapath(datapath, tokenizer, + max_qa_length, + max_seq_length)) + + print_rank_0(' >> total number of samples: {}'.format( + len(self.samples))) + + # This indicates that each "sample" has multiple samples that + # will collapse into batch dimension + self.sample_multiplier = NUM_CHOICES + + def __len__(self): + return len(self.samples) + + def __getitem__(self, idx): + return self.samples[idx] + + +def process_single_datapath(datapath, tokenizer, max_qa_length, max_seq_length): + """Read in RACE files, combine, clean-up, tokenize, and convert to + samples.""" + + print_rank_0(' > working on {}'.format(datapath)) + start_time = time.time() + + # Get list of files. + filenames = glob.glob(os.path.join(datapath, '*.txt')) + + samples = [] + num_docs = 0 + num_questions = 0 + num_samples = 0 + # Load all the files + for filename in filenames: + with open(filename, 'r') as f: + for line in f: + data = json.loads(line) + num_docs += 1 + + context = data["article"] + questions = data["questions"] + choices = data["options"] + answers = data["answers"] + # Check the length. + assert len(questions) == len(answers) + assert len(questions) == len(choices) + + # Context: clean up and convert to ids. + context = clean_text(context) + context_ids = tokenizer.tokenize(context) + + # Loop over questions. + for qi, question in enumerate(questions): + num_questions += 1 + # Label. + label = ord(answers[qi]) - ord("A") + assert label >= 0 + assert label < NUM_CHOICES + assert len(choices[qi]) == NUM_CHOICES + + # For each question, build num-choices samples. + ids_list = [] + types_list = [] + paddings_list = [] + for ci in range(NUM_CHOICES): + choice = choices[qi][ci] + # Merge with choice. + if "_" in question: + qa = question.replace("_", choice) + else: + qa = " ".join([question, choice]) + # Clean QA. + qa = clean_text(qa) + # Tokenize. + qa_ids = tokenizer.tokenize(qa) + # Trim if needed. + if len(qa_ids) > max_qa_length: + qa_ids = qa_ids[0:max_qa_length] + + # Build the sample. + ids, types, paddings \ + = build_tokens_types_paddings_from_ids( + qa_ids, context_ids, max_seq_length, + tokenizer.cls, tokenizer.sep, tokenizer.pad) + + ids_list.append(ids) + types_list.append(types) + paddings_list.append(paddings) + + # Convert to numpy and add to samples + samples.append(build_sample(ids_list, types_list, + paddings_list, label, + num_samples)) + num_samples += 1 + + elapsed_time = time.time() - start_time + print_rank_0(' > processed {} document, {} questions, and {} samples' + ' in {:.2f} seconds'.format(num_docs, num_questions, + num_samples, elapsed_time)) + + return samples diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/race/finetune.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/race/finetune.py new file mode 100644 index 0000000000000000000000000000000000000000..e03f927ceb00dcca4da7e5fedd740108f32574fd --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/race/finetune.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed 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. + +"""Race.""" + +from megatron import get_args +from megatron import print_rank_0 +from megatron import get_tokenizer +from megatron import mpu +from megatron.model.multiple_choice import MultipleChoice +from tasks.eval_utils import accuracy_func_provider +from tasks.finetune_utils import finetune +from tasks.race.data import RaceDataset + + +def train_valid_datasets_provider(): + """Provide train and validation datasets.""" + args = get_args() + tokenizer = get_tokenizer() + + train_dataset = RaceDataset('training', args.train_data, + tokenizer, args.seq_length) + valid_dataset = RaceDataset('validation', args.valid_data, + tokenizer, args.seq_length) + + return train_dataset, valid_dataset + + +def model_provider(pre_process=True, post_process=True): + """Build the model.""" + + print_rank_0('building multichoice model for RACE ...') + model = MultipleChoice(num_tokentypes=2, + pre_process=pre_process, + post_process=post_process) + + return model + + +def metrics_func_provider(): + """Privde metrics callback function.""" + args = get_args() + tokenizer = get_tokenizer() + + def single_dataset_provider(datapath): + name = datapath.split('RACE')[-1].strip('/').replace('/', '-') + return RaceDataset(name, [datapath], tokenizer, args.seq_length) + + return accuracy_func_provider(single_dataset_provider) + + +def main(): + + finetune(train_valid_datasets_provider, model_provider, + end_of_epoch_callback_provider=metrics_func_provider) diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/tasks_args.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/tasks_args.py new file mode 100644 index 0000000000000000000000000000000000000000..1e06798dbb4414e439e0e9e8b38d446abd41efe1 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/tasks_args.py @@ -0,0 +1,60 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed 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. + +def get_tasks_args(parser): + """Provide extra arguments required for tasks.""" + group = parser.add_argument_group(title='tasks') + + group.add_argument('--task', type=str, required=True, + help='Task name.') + group.add_argument('--model-type', default='GPT', type=str, + help='Type of Model', choices=['GPT', 'LLAMA']) + group.add_argument('--epochs', type=int, default=None, + help='Number of finetunning epochs. Zero results in ' + 'evaluation only.') + group.add_argument('--pretrained-checkpoint', type=str, default=None, + help='Pretrained checkpoint used for finetunning.') + group.add_argument('--keep-last', action='store_true', + help='Keep the last batch (maybe incomplete) in' + 'the data loader') + group.add_argument('--train-data', nargs='+', default=None, + help='Whitespace separated paths or corpora names ' + 'for training.') + group.add_argument('--valid-data', nargs='*', default=None, + help='path(s) to the validation data.') + group.add_argument('--overlapping-eval', type=int, default=32, + help='Sliding window for overlapping evaluation.') + group.add_argument('--strict-lambada', action='store_true', + help='Use more difficult formulation of lambada.') + # Retriever args + group.add_argument('--qa-data-dev', type=str, default=None, + help='Path to the QA dataset dev file.') + group.add_argument('--qa-data-test', type=str, default=None, + help='Path to the QA dataset test file.') + + # Faiss arguments for retriever + group.add_argument('--faiss-use-gpu', action='store_true', + help='Whether create the FaissMIPSIndex on GPU') + group.add_argument('--faiss-match', type=str, default='string', \ + choices=['regex', 'string'], help="Answer matching '\ + 'logic type") + group.add_argument('--faiss-topk-retrievals', type=int, default=100, + help='Number of blocks to use as top-k during retrieval') + + # checkpoint manipulations + group.add_argument('--checkpoint-override-tokenizer', action='store_true', + help='If set, override checkpoint tokenizer information with current args') + + return parser diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/zeroshot_gpt/detokenizer.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/zeroshot_gpt/detokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..2bc87286dbd9c05b4219c342f42639070c161e8c --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tasks/zeroshot_gpt/detokenizer.py @@ -0,0 +1,80 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed 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. + +"""Detokenization.""" + +import re + + +def ptb_detokenizer(string): + string = string.replace(" '", "'") + string = string.replace(" \n", "\n") + string = string.replace("\n ", "\n") + string = string.replace(" n't", "n't") + string = string.replace(" N ", "1 ") + string = string.replace("$ 1", "$1") + string = string.replace("# 1", "#1") + return string + + +def wikitext_detokenizer(string): + # contractions + string = string.replace("s '", "s'") + string = re.sub(r"/' [0-9]/", r"/'[0-9]/", string) + # number separators + string = string.replace(" @-@ ", "-") + string = string.replace(" @,@ ", ",") + string = string.replace(" @.@ ", ".") + # punctuation + string = string.replace(" : ", ": ") + string = string.replace(" ; ", "; ") + string = string.replace(" . ", ". ") + string = string.replace(" ! ", "! ") + string = string.replace(" ? ", "? ") + string = string.replace(" , ", ", ") + # double brackets + string = re.sub(r"\(\s*([^\)]*?)\s*\)", r"(\1)", string) + string = re.sub(r"\[\s*([^\]]*?)\s*\]", r"[\1]", string) + string = re.sub(r"{\s*([^}]*?)\s*}", r"{\1}", string) + string = re.sub(r"\"\s*([^\"]*?)\s*\"", r'"\1"', string) + string = re.sub(r"'\s*([^']*?)\s*'", r"'\1'", string) + # miscellaneous + string = string.replace("= = = =", "====") + string = string.replace("= = =", "===") + string = string.replace("= =", "==") + string = string.replace(" " + chr(176) + " ", chr(176)) + string = string.replace(" \n", "\n") + string = string.replace("\n ", "\n") + string = string.replace(" N ", " 1 ") + string = string.replace(" 's", "'s") + + return string + + +def lambada_detokenizer(string): + return string + + +_DETOKENIZERS = { + 'ptb': ptb_detokenizer, + 'wiki': wikitext_detokenizer, + 'lambada': lambada_detokenizer, +} + + +def get_detokenizer(path): + for key in _DETOKENIZERS.keys(): + if key in path: + return _DETOKENIZERS[key] diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/convert_checkpoint/README.md b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/convert_checkpoint/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3f74bb1aa4f7dfc690a24b82218e5a7e94e66354 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/convert_checkpoint/README.md @@ -0,0 +1,78 @@ +# Introduction + +This folder is a collection of scripts for converting checkpoints of one training framework (e.g., DeepSpeed) into that of a different framework (e.g., Megatron-LM, HF Transformers). + +The folder also contains scripts for inspecting checkpoint files and folders, which could be useful when developing checkpoint conversion logic. At the time of creation, this folder contains scripts to convert DeepSpeed checkpoints to Megatron-LM and HF Transformers checkpoints (this motivated this effort as part of the BigScience project). + +Here are the list and details of checkpoint conversions provided by the available scripts: + +1. [Megatron-DeepSpeed to Megatron-LM](#Megatron-DeepSpeed-to-Megatron) +1. [Megatron-DeepSpeed to HF Transformers](#Megatron-DeepSpeed-to-HF-Transformers) + + +## Megatron-DeepSpeed to Megatron + +The (current implementation of the) converter extracts args and model parameters from a DeepSpeed checkpoint (i.e., excludes other training states such as optimizer, scheduler, etc) and convert into a Megatron-LM checkpoint similarly containing only model parameters. The converter also provides a best-effort attempt to reshape the tensor-parallelism and pipeline parallelism degrees for the checkpoint. The resulting Megatron-LM checkpoint could be loaded into Megatron-LM framework for finetuning or inference. Tensor parallelism (TP) and pipeline parallelism (PP) are supported in the sense that the generated Megatron-LM checkpoint (folders and files) will be of the same TP and PP of the training that created the input DeepSpeed checkpoint. The entry point of the converter is `deepspeed_to_megatron.py`, which as the following usage: +```bash +python tools/convert_checkpoint/deepspeed_to_megatron.py -h +Convert DeepSpeed Checkpoint to Megatron Checkpoint +usage: deepspeed_to_megatron.py [-h] [--input_folder INPUT_FOLDER] + [--output_folder OUTPUT_FOLDER] + [--target_tp TARGET_TP] + [--target_pp TARGET_PP] [--for_release] + +optional arguments: + -h, --help show this help message and exit + --input_folder INPUT_FOLDER + Input DeepSpeed Checkpoint folder + --output_folder OUTPUT_FOLDER + Output Megatron checkpoint folder + --target_tp TARGET_TP + Target TP degree + --target_pp TARGET_PP + Target PP degree + --for_release Convert for release purpose, reset some (progress) + counters. +``` + +The following scripts which proved useful for debugging are also included: +1. `inspect_deepspeed_checkpoint.py`: view the contents of a DeepSpeed checkpoint folder. +2. `inspect_checkpoint.py`: view the contents of a PyTorch checkpoint file. + +## Megatron-DeepSpeed to HF Transformers + +In order to convert from Megatron-DeepSpeed to HF Transformers, you can do this directly using: + +```bash +python tools/convert_checkpoint/deepspeed_to_transformers.py \ +--input_folder /path/to/Megatron-Deepspeed/checkpoint/global_step97500 \ +--output_folder /path/to/transformers/checkpoint +``` +since `transformers` currently only works with PP=1/TP=1 we use the defaults `--target_tp 1 --target_pp 1`. + +The script taps into `transformers` and as of this writing requires `transformers@master` (or `transformers==4.11` if you read this later and a new version is released). + +Note that you may run into problems with not having `megatron.enums` defined since `Megatron-Deepspeed` in the `bigscience-workshop` tree diverged from the `microsoft` tree. In such cases you can fix this on the fly by ensuring the former appears first in the `sys.path`. For example: + + +```bash +PYTHONPATH=/hf/Megatron-DeepSpeed-bigscience:/hf/Megatron-DeepSpeed-microsoft \ +python tools/convert_checkpoint/deepspeed_to_transformers.py \ +--input_folder /path/to/Megatron-Deepspeed/checkpoint/global_step97500 \ +--output_folder /path/to/transformers/checkpoint +``` + +Alternatively, you can convert first from Megatron-DeepSpeed to Megatron and then to HF Transformers: + +```bash +# 1. Megatron-DeepSpeed to Megatron +cd /hf/Megatron-DeepSpeed-bigscience +python tools/convert_checkpoint/deepspeed_to_megatron.py --target_tp 1 --target_pp 1 \ +--input_folder /path/to/Megatron-Deepspeed/checkpoint/global_step97500 \ +--output_folder /path/to/Megatron/checkpoint + +# 2. Megatron to HF Transformers +cd /hf/transformers +python src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py \ +/path/to/Megatron/checkpoint/iter_0097500/mp_rank_00/model_optim_rng.pt +``` diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/convert_checkpoint/__init__.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/convert_checkpoint/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dd175ceedb8ef2c9170a38b378510ef85945016f --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/convert_checkpoint/__init__.py @@ -0,0 +1 @@ +from .verify_checkpoint_non_tp_consistency import verify_checkpoint \ No newline at end of file diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/convert_checkpoint/inspect_checkpoint.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/convert_checkpoint/inspect_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..151041cb4ba8bd8606d1a35d15ec7fedc44684f3 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/convert_checkpoint/inspect_checkpoint.py @@ -0,0 +1,40 @@ +import torch +import sys +import os +from collections import OrderedDict + + +def dump_data(datum, name_list=[]): + if type(datum) in (dict, OrderedDict): + for k, v in datum.items(): + dump_data(v, name_list+[str(k)]) + elif type(datum) in (list, tuple): + for v in datum: + dump_data(v, name_list) + elif torch.is_tensor(datum): + prefix = '.'.join(name_list) + print(f'[tensor] {prefix} = {datum.shape}') + else: + #pass + prefix = '.'.join(name_list) + print(f'[other] {prefix} = {datum}') + +def main(): + if len(sys.argv) < 2: + print(f'Usage: {sys.argv[0]} ') + exit(1) + + ckpt_file = sys.argv[1] + if not os.path.isfile(ckpt_file): + print(f'{ckpt_file} is not a valid file') + exit(1) + + print(f'loading checkpoint file: {ckpt_file}') + sd = torch.load(ckpt_file, map_location=torch.device('cpu')) + dump_data(sd) + + quit() + + +if __name__ == "__main__": + main() diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/convert_checkpoint/inspect_deepspeed_checkpoint.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/convert_checkpoint/inspect_deepspeed_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..3125f7d9a78eb3e3ff54d8d324e358d2d556eb57 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/convert_checkpoint/inspect_deepspeed_checkpoint.py @@ -0,0 +1,80 @@ +import argparse +from deepspeed_checkpoint import DeepSpeedCheckpoint + +def list_files(file_list, tag): + print(f'Listing files: {tag}') + for i, file in enumerate(file_list): + print(f'{i+1}: {file}') + +def parse_arguments(): + parser = argparse.ArgumentParser() + parser.add_argument('--folder', default=None, type=str, help='DeepSpeed Checkpoint folder') + parser.add_argument('--target_tp', default=None, type=int, help='Target TP degree') + parser.add_argument('--target_pp', default=None, type=int, help='Target PP degree') + args = parser.parse_args() + print(f'args = {args}') + return args + + +def show_input_files(ds_checkpoint): + list_files(ds_checkpoint.file_list, 'all') + list_files(ds_checkpoint.zero_files, 'zero') + list_files(ds_checkpoint.layer_files, 'layer') + list_files(ds_checkpoint.mp_rank_files, 'mp rank') + +def show_simple_state(ds_checkpoint): + print(f'layer keys = {ds_checkpoint.layer_keys}') + print(f'layer count = {ds_checkpoint.layer_count}') + + print(f'tp_degree_count = {ds_checkpoint.tp_degree}') + print(f'pp_degree_count = {ds_checkpoint.pp_degree}') + print(f'dp_degree_count = {ds_checkpoint.dp_degree}') + +def show_mappings(ds_checkpoint): + ds_checkpoint.show_pp_tranformer_map() + ds_checkpoint.show_transformer_file_map() + ds_checkpoint.show_tp_embedding_map() + ds_checkpoint.show_tp_final_norm_map() + +def show_state_summary(tag, sd): + summary = {k:v.shape for k,v in sd.items()} + print(f'{tag} = {summary}') + +def show_embedding_states(ds_checkpoint): + for i in range(0, ds_checkpoint.tp_degree): + sd = ds_checkpoint.get_embedding_state(i) + show_state_summary(f'embedding[{i}]', sd) + +def show_final_norm_states(ds_checkpoint): + for i in range(0, ds_checkpoint.tp_degree): + sd = ds_checkpoint.get_final_norm_state(i) + show_state_summary(f'final_norm[{i}]', sd) + +def show_transformer_states(ds_checkpoint): + for i in range(0, ds_checkpoint.tp_degree): + for j in range(0, ds_checkpoint.pp_degree): + state_list = ds_checkpoint.get_transformer_state(tp_index=i, pp_index=j) + print(f'tp_pp_rank[{i},{j}] = ') + for k, sd in enumerate(state_list): + show_state_summary(f' block[{k}]', sd) + print("") + + +def main(): + print(f'Inspecting DeepSpeed Checkpoint') + args = parse_arguments() + + ds_checkpoint = DeepSpeedCheckpoint(args.folder, args.target_tp, args.target_pp) + ds_checkpoint.validate_files() + + show_input_files(ds_checkpoint) + show_simple_state(ds_checkpoint) + show_mappings(ds_checkpoint) + show_embedding_states(ds_checkpoint) + show_final_norm_states(ds_checkpoint) + show_transformer_states(ds_checkpoint) + checkpoint_args = ds_checkpoint.get_args() + print(f'checkpoint args = {checkpoint_args}') + +if __name__ == "__main__": + main() diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/create_synthetic_dataset.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/create_synthetic_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..b5ecf52193d29ed2eb8caecc20743b59eb0dbbf7 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/create_synthetic_dataset.py @@ -0,0 +1,34 @@ +# Copyright (C) 2023 Habana Labs, Ltd. an Intel Company + +import argparse +import numpy as np + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) + parser.add_argument( + '--valid_files_path', + type=str, + default='c4_en_validation_c4_spm_text_document', + help='Path to the name of the valid files without an extension.') + parser.add_argument( + '--output_path', + type=str, + default='/tmp/', + help='Output path') + args = parser.parse_args() + + HEADER_END=17 + SHUFFLE_END=24567*2+14 + + document_bin = np.fromfile(args.valid_files_path + ".bin", dtype=np.uint16) + document_bin = np.random.randint(1, high=50256, size=document_bin.size, dtype=np.uint16) % 50256 + + document_idx = np.fromfile(args.valid_files_path + ".idx", dtype=np.uint16) + document_idx_sizes = document_idx[HEADER_END:SHUFFLE_END:2] + document_idx_sizes = np.random.shuffle(document_idx_sizes) + + with open(args.output_path+"synthetic_text_document.bin", 'wb') as f: + document_bin.tofile(f) + with open(args.output_path+"synthetic_text_document.idx", 'wb') as f: + document_idx.tofile(f) \ No newline at end of file diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/linter.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/linter.py new file mode 100644 index 0000000000000000000000000000000000000000..5b14007666600746341e2b962b7b09e69f3019f0 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/linter.py @@ -0,0 +1,36 @@ +import os +import os.path as osp +import pathlib +import subprocess + + +def recursively_lint_files(): + """Recursively lint all python files in chosen subdirectories of megatron-lm""" + + try: + import autopep8 + except ModuleNotFoundError: + print("Please first install autopep8 via `pip install autopep8`") + return + + # get all python file paths from top level directory + file_dir = str(pathlib.Path(__file__).parent.absolute()) + working_dir = osp.join(file_dir, os.pardir) + all_py_paths = set(os.path.join(working_dir, fname) + for fname in os.listdir(working_dir) if ".py" in fname) + + # get all python file paths from chosen subdirectories + check_dirs = ['docker', 'megatron', 'openwebtext', 'scripts', 'tasks'] + for sub_dir in check_dirs: + for path, _, fnames in os.walk(osp.join(working_dir, sub_dir)): + all_py_paths.update(set(osp.join(path, fname) for fname in fnames if ".py" in fname)) + + print("Linting the following: ") + for py_path in all_py_paths: + print(py_path) + command = 'autopep8 --max-line-length 100 --aggressive --in-place {}'.format(py_path) + subprocess.check_call(command) + + +if __name__ == "__main__": + recursively_lint_files() diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/openwebtext/README.md b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/openwebtext/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7d0b43940b1d038f530669cf3b8351b991575ef2 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/openwebtext/README.md @@ -0,0 +1,59 @@ +The following steps show how to prepare training dataset to train the mode. + +# Libraries to install + +``` + pip install ftfy langdetect numpy torch pandas nltk sentencepiece boto3 tqdm regex bs4 newspaper3k htmlmin tldextract + git clone https://github.com/mattilyra/LSH + cd LSH + python setup.py install +``` + +# Download the dataset + +1. Download the deduplicated URLs from [jcpeterson](https://mega.nz/#F!EZZD0YwJ!9_PlEQzdMVLaNdKv_ICNVQ!cc4RgQQZ) +2. Remove blacklisted URLs. +``` +python blacklist_urls.py +``` +3. Download the content from the clean urls with [openwebtext's utilities](https://github.com/eukaryote31/openwebtext/blob/master/download.py). + +4. Merge the contents into one loose json file with 1 json per newline of the format `{'text': text, 'url': unique_url}`. It is important for the url to be unique. + +# Prepare the data for GPT-2 training: + +1. Perform ftfy, english detection and remove documents with less than 128 tokens. This step can be sharded and run on shards. +``` +python cleanup_dataset.py +``` +Additional cleanup (e.g. remove documents less than 512 characters or dataset specific cleaning like stories, realnews datasets) can be done using `cleanup_fix_dataset.py`. More details can be found by running `python cleanup_fix_dataset.py --help`. +2. Using LSH, find possible duplicates and store then in a file for later processing. The code supports saving and loading fingerprints for recurrent deduplications, and is also multithreaded for faster processing. More details are can be found by `python find_duplicate.py --help`. +``` +python find_duplicates.py --inputs --output +``` +3. Based on similarity measure defind inside function `is_similar` (default: 0.9), group urls that are similar. Basically, for each group, only one url we should keep and remove the rest. +``` +python group_duplicate_urls.py +``` +4. Remove similar documents that were detected in the last step. +``` +python remove_group_duplicates.py +``` + +5. Shuffle the dataset. +``` +shuf -o train_data.json +``` + +# Deduplicating ngrams + +To deduplicate the downstream tasks (e.g. lambada, squad) from the training dataset, we run the following command. + +``` +python filter_ngrams.py --tasks --dedup-dataset --output +``` +We use 13-grams by default for the deduplication. When we find a 13-gram match in a training document, we split the document into two pieces and remove the 13-gram along with 200 characters from the both side of the 13-gram. We also remove any splitted document with less than 200 characters or if a document got splitted more than 10 times. These parameters can be changed using corresponding arguments. + +Only for the lambada task, we need to provide the path, `--lambada-path `. + +Several other features (e.g. save and load dictionary) have been added, look at `python filter_ngrams.py --help` for details. diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/openwebtext/blacklist_urls.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/openwebtext/blacklist_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..d9c6f20ad76b20742e6ce8dcc634833705901f92 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/openwebtext/blacklist_urls.py @@ -0,0 +1,312 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed 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 glob +import re +import time +import tldextract +import sys + + +# List of the domains to blacklist. +domain_blacklist = set([ + '500px', + 'aapks', + 'akamaihd', + 'amazon', + 'apple', + 'artifactfire', + 'artstation', + 'awwni', + 'bandcamp', + 'battleforthenet', + 'coinscalendar', + 'dailymotion', + 'deviantart', + 'discord', + 'discordapp', + 'dlapkandroid', + 'dropbox', + 'e621', + 'ebay', + 'edealinfo', + 'erome', + 'eroshare', + 'explosm', + 'facebook', + 'fbcdn', + 'flickr', + 'furaffinity', + 'futhead', + 'gatopardo', + 'gfycat', + 'gifsound', + 'gifsoup', + 'giphy', + 'github', + 'google', + 'gunprime', + 'gyazo', + 'hotdealstar', + 'imagefap', + 'imageshack', + 'imgflip', + 'imgur', + 'instagram', + 'karmadecay', + 'kryptocal', + 'kym-cdn', + 'liveleak', + 'livememe', + 'lmgtfy', + 'magaimg', + 'memegenerator', + 'minorplanetcenter', + 'minus', + 'mobafire', + 'morejpeg', + 'nocookie', + 'pcpartpicker', + 'photobucket', + 'pinimg', + 'pinterest', + 'pixiv', + 'pornhub', + 'prntscr', + 'puu', + 'qkme', + 'quickmeme', + 'radd', + 'redd', + 'reddit', + 'reddit-stream', + 'redditlog', + 'redditmedia', + 'reddituploads', + 'redtube', + 'reupp', + 'reverb', + 'roanoke', + 'rollingstone', + 'sli', + 'soundcloud', + 'soundgasm', + 'spankbang', + 'spotify', + 'strawpoll', + 'streamable', + 'timeanddate', + 'tinypic', + 'touhouradio', + 'tumblr', + 'twimg', + 'twitch', + 'twitter', + 'vid', + 'vimeo', + 'vine', + 'vkaao', + 'vocaroo', + 'voyagefusion', + 'walmart', + 'wciu', + 'wikimedia', + 'wikipedia', + 'xhamster', + 'xkcd', + 'xvideos', + 'youtu', + 'youtube', + 'youtubedoubler', + 'ytimg', + 'zillexplorer', +]) + +def domain_is_in_blacklist(url): + domain = tldextract.extract(url).domain + return domain in domain_blacklist + + +# List of extentions to blacklist. +extentions_blacklist = ( + '.3gp', + '.7z' + '.ai', + '.aif', + '.apk', + '.app', + '.avi', + '.bin', + '.bmp', + '.bz2', + '.css', + '.csv', + '.dat', + '.deb', + '.dmg', + '.doc', + '.docx', + '.exe', + '.gif', + '.gifv', + '.gz', + '.iso', + '.jar', + '.jpeg', + '.jpg', + '.js', + '.log', + '.mid', + '.midi', + '.mkv', + '.mov', + '.mp3', + '.mp4', + '.mpeg', + '.mpg', + '.ogg', + '.ogv', + '.otf', + '.pdf', + '.pkg', + '.png', + '.pps', + '.ppt', + '.pptx', + '.psd', + '.py', + '.qt', + '.ram', + '.rar', + '.sql', + '.svg', + '.swf', + '.tar.gz', + '.tar', + '.tgz', + '.tiff', + '.ttf', + '.txt', + '.wav', + '.webm', + '.wma', + '.wmv', + '.xls', + '.xlsx', + '.xml', + '.xz', + '.zip', +) + +def extention_is_in_blacklist(url): + if url.split('?')[0].lower().endswith(extentions_blacklist): + return True + return False + + +# Malformed urls. +# This function is adapted from: +# https://stackoverflow.com/questions/7160737/python-how-to-validate-a-url-in-python-malformed-or-not +url_regex = re.compile( + r'^(?:http)s?://' # http:// or https:// + r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain... + r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip + r'(?::\d+)?' # optional port + r'(?:/?|[/?]\S+)$', re.IGNORECASE) +def url_is_malformed(url): + return re.match(url_regex, url) is None + + +def print_progress(prefix, start_time, urls_counter, + domain_blacklist_counter, + extention_blacklist_counter, + short_url_counter, malformed_url_counter, + duplicate_url_counter): + string = prefix + ' | ' + string += 'time elapsed (s): {:.2f} | '.format(time.time() - start_time) + string += 'number of urls: {} | '.format(urls_counter) + string += 'domain blacklisted: {} | '.format(domain_blacklist_counter) + string += 'extention blacklisted: {} | '.format(extention_blacklist_counter) + string += 'short urls (<=8): {} | '.format(short_url_counter) + string += 'malformed urls: {} | '.format(malformed_url_counter) + string += 'duplicate urls: {}'.format(duplicate_url_counter) + print(string, flush=True) + + +if __name__ == '__main__': + + + print('remove blacklisted urls ..') + + # Path to the url files. + path = sys.argv[1] + # Output url file. + output = sys.argv[2] + + # Get the list of url files. + files = glob.glob(path + '/*.txt') + print('> found {} files'.format(len(files))) + + urls = set() + urls_counter = 0 + domain_blacklist_counter = 0 + extention_blacklist_counter = 0 + short_url_counter = 0 + malformed_url_counter = 0 + duplicate_url_counter = 0 + start_time = time.time() + for filename in files: + with open(filename, 'r') as f: + for line in f: + url = line.strip() + urls_counter += 1 + if domain_is_in_blacklist(url): + print('[DOMAIN BLACKLIST]: {}'.format(url), flush=True) + domain_blacklist_counter += 1 + elif extention_is_in_blacklist(url): + print('[EXTENTION BLACKLIST]: {}'.format(url), flush=True) + extention_blacklist_counter += 1 + elif len(url) <= 8: + print('[SHORT URL]: {}'.format(url), flush=True) + short_url_counter += 1 + elif url_is_malformed(url): + print('[MALFORMED URL]: {}'.format(url), flush=True) + malformed_url_counter += 1 + elif url in urls: + print('[DUPLICATE URL]: {}'.format(url), flush=True) + duplicate_url_counter += 1 + else: + urls.add(url) + if urls_counter % 100000 == 0: + print_progress('PROGRESS', start_time, urls_counter, + domain_blacklist_counter, + extention_blacklist_counter, + short_url_counter, malformed_url_counter, + duplicate_url_counter) + + print_progress('FINAL', start_time, urls_counter, + domain_blacklist_counter, + extention_blacklist_counter, + short_url_counter, malformed_url_counter, + duplicate_url_counter) + + # Write the final set of urls. + print('> writing cleaned up url list to {}'.format(output)) + with open(output, 'w') as f: + for url in urls: + f.write(url + '\n') + + print('done :-)') diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/openwebtext/cleanup_fix_dataset.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/openwebtext/cleanup_fix_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..0ed018ed43b90b535e057224aad7bc86463e8006 --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/openwebtext/cleanup_fix_dataset.py @@ -0,0 +1,191 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed 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. + +""" +Filter and clean documents: +Capable to clean docs with less than 512 characters, less than +256 characters and contains javascript, fix text and dataset specific +cleaning like stories and realnews datasets. +Program arguments have the details. +""" + +import argparse +from functools import partial +import glob +import ftfy +import json +from langdetect import detect +import multiprocessing +import os +from pathlib import Path +import re +import time + +def process_doc(json_line, args): + + # Read the line. + document = json.loads(json_line) + text = document['text'] + + output = {'remove_512': False, 'remove_256_javascript': False, \ + 'remove_512_non_english': False, 'ftfy_fix_text': False, \ + 'general_cleaning': False} + + try: + # Reomove all docs with less than 512 characters + if "remove_512" in args.tasks: + if len(text) < 512: + output['remove_512'] = True + return output, text, document, True + + # Remove docs if less than 256 character length and contains Javascript + if "remove_256_javascript" in args.tasks: + if len(text) < 256 and 'javascript' in text.lower(): + output['remove_256_javascript'] = True + return output, text, document, True + + # Remove docs < 512 and nonenglish + if "remove_512_non_english" in args.tasks: + if len(text) < 512 and detect(text) != 'en': + output['remove_512_non_english'] = True + return output, text, document, True + + # Fix the text using ftfy, don't remove the text, hence return False + if "ftfy_fix_text" in args.tasks: + fixed_text = ftfy.fix_text(text) + output['ftfy_fix_text'] = True + return output, fixed_text, document, False + + # Cleaning extra spaces and newlines + if "general_cleaning" in args.tasks: + cleaned_text = re.sub(r" +|\b\n+ |\b\n+", " ", text) + #cleaned_text = re.sub(r"\n\n+", "\n\n", text) # used this for Gutenberg dataset + #cleaned_text = re.sub(r"\n", "\n\n", text) # Used this for realnews + + # stories datasets + #cleaned_text = re.sub(r" \'", "'", text) + #cleaned_text = re.sub(r" \!", "!", cleaned_text) + #cleaned_text = re.sub(r" \.", ".", cleaned_text) + #cleaned_text = re.sub(r" \?", "?", cleaned_text) + #cleaned_text = re.sub(r" - ", "-", cleaned_text) + ##cleaned_text = re.sub(r"\" ", "\"", cleaned_text) + #cleaned_text = re.sub(r" @ ", "@", cleaned_text) + + output['general_cleaning'] = True + return output, cleaned_text, document, False + + except Exception as e: + print('Error: *************************\n{}\ntext: {}'.format(e, \ + text), flush=True) + return output, text, document, True + + # don't remove + return output, text, document, False + + +def process_set(args, input_file, output_f_cleaned, output_f_filtered): + + print(' > working on {} ...'.format(input_file), flush=True) + + num_docs = num_remove_512 = num_remove_java = num_remove_512_non_english \ + = num_ftfy_fix_text = num_general_cleaning = 0 + + # Output file and counters. + output_cleaned = open(output_f_cleaned, 'wb') + output_filtered = open(output_f_filtered, 'wb') + + start_time = time.time() + + # Setup multi-processing. + num_workers = 40 + fin = open(input_file, 'r', encoding='utf-8') + pool = multiprocessing.Pool(num_workers) + process_doc_partial = partial(process_doc, args=args) + processed_docs = pool.imap(process_doc_partial, fin, 500) + + # Process documents. + for output, text, document, to_filter in processed_docs: + num_docs += 1 + + num_remove_512 += 1 if output['remove_512'] else 0 + num_remove_java += 1 if output['remove_256_javascript'] else 0 + num_remove_512_non_english += 1 if output['remove_512_non_english'] \ + else 0 + num_ftfy_fix_text += 1 if output['ftfy_fix_text'] else 0 + num_general_cleaning += 1 if output['general_cleaning'] else 0 + + document['text'] = text + myjson = json.dumps(document, ensure_ascii=False) + + if to_filter: + output_filtered.write(myjson.encode('utf-8')) + output_filtered.write('\n'.encode('utf-8')) + else: + output_cleaned.write(myjson.encode('utf-8')) + output_cleaned.write('\n'.encode('utf-8')) + + if num_docs % args.log_interval == 0: + print(' processed {:9d} documents in {:.2f} seconds ...'.format( + num_docs, time.time() - start_time), flush=True) + + # Close the file. + output_cleaned.close() + output_filtered.close() + fin.close() + + # Print stats. + print(' >> total docs: {} remove_512 {} remove_256_javascript {} '\ + 'remove_512_non_english {} ftfy_fix_text {} general_cleaning {}'.\ + format(num_docs, num_remove_512, num_remove_java,\ + num_remove_512_non_english, num_ftfy_fix_text, \ + num_general_cleaning), flush=True) + +if __name__ == '__main__': + + + print('parsing the arguments ...') + + parser = argparse.ArgumentParser() + parser.add_argument('--input-files', nargs = '*', required=True, default=\ + None, help = 'Input json files that needs to be'\ + ' cleaned') + parser.add_argument('--tasks', nargs = '*', required=True, default=None,\ + help = 'Tasks to perform on the input files, ' \ + 'such as remove_512, remove_256_javascript, ' \ + 'remove_512_non_english, ftfy_fix_text, and ' \ + 'general_cleaning. 256 or 512 means the number' \ + ' of characters.') + + parser.add_argument('--output-path', type=str, default=None, + help='Directory where the output should go') + parser.add_argument('--log-interval', type=int, default=100, + help='Log interval') + + args = parser.parse_args() + + print('cleanup dataset ...') + + for input_file in args.input_files: + input_filename, input_filename_ext = os.path.splitext(Path(input_file)\ + .name) + + output_f_cleaned = os.path.join(args.output_path, input_filename + \ + "_cleaned" + input_filename_ext) + output_f_filtered = os.path.join(args.output_path, input_filename + \ + "_filtered" + input_filename_ext) + + process_set(args, input_file, output_f_cleaned, output_f_filtered) + + print('done :-)', flush=True) diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/openwebtext/find_duplicates.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/openwebtext/find_duplicates.py new file mode 100644 index 0000000000000000000000000000000000000000..09e9381bebcd3b01ae1b8a0f9076f93290e987da --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/openwebtext/find_duplicates.py @@ -0,0 +1,305 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed 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 argparse +from functools import partial +import itertools +import json +from lsh import cache, minhash +import multiprocessing +import numpy as np +import time +import pickle +import sys +import os + +# This function is adapted from: +# https://github.com/mattilyra/LSH/blob/master/examples/Introduction.ipynb +def shingles(text, char_ngram=5): + return set(text[head:head + char_ngram] + for head in range(0, len(text) - char_ngram)) + + +# This function is adapted from: +# https://github.com/mattilyra/LSH/blob/master/examples/Introduction.ipynb +def jaccard(set_a, set_b, args): + if len(set_a) < 1 or len(set_b) < 1: + return 0.0 + + intersection = set_a & set_b + union = set_a | set_b + + if args.jaccard == 'min': + return len(intersection) / min(len(set_a), len(set_b)) + elif args.jaccard == 'max': + return len(intersection) / max(len(set_a), len(set_b)) + else: + return len(intersection) / len(union) + +def compute_fingerprint(line, key): + try: + myjson = json.loads(line) + url = myjson[key] + text = myjson['text'] + fingerprint = hasher.fingerprint(text) + except Exception as e: + print('Error:', e) + return None, None, None, False + + return url, text, fingerprint, True + +def url_pairs_to_remove(args, bucket_urls, url_doc): + remove_urls_list = [] + deduped_local, counter_local = 0, 0 + iteration = 0 + while len(bucket_urls) > 1: + if args.heuristic_iter != -1 and \ + iteration == args.heuristic_iter: + break + + items = list(bucket_urls) + remove_urls = [] + main_url = items[np.random.randint(0, len(items))] + main_dhingles = shingles(url_doc[main_url]) + + for i in range(0, len(items)): + counter_local += 1 + other_url = items[i] + if other_url == main_url: + continue + other_shingles = shingles(url_doc[other_url]) + try: + jaccard_sim = jaccard(main_dhingles, other_shingles, args) + except Exception as e: + print('Error:', e) + jaccard_sim = 0.0 + if jaccard_sim > 0.5: + remove_urls.append({other_url: jaccard_sim}) + deduped_local += 1 + bucket_urls.remove(other_url) + + bucket_urls.remove(main_url) + if len(remove_urls) > 0: + remove_urls_list.append({main_url: remove_urls}) + iteration += 1 + return remove_urls_list, deduped_local, counter_local + +def write_remove_urls_list(remove_urls_list, f_out): + if len(remove_urls_list) > 0: + for each_url_remove in remove_urls_list: + myjson = json.dumps(each_url_remove, ensure_ascii=False) + f_out.write(myjson.encode('utf-8')) + f_out.write('\n'.encode('utf-8')) + +def compute_jaccard(each_bin, num_bins, start_time_local): + + remove_urls_list = [] + deduped_local, counter_local, bucket_local = 0, 0, 0 + + for bucket_id in each_bin: + bucket_local += 1 + if os.getpid() % num_bins == 0 and bucket_local % 100000 == 0: + print("Counter {}, progress {:.2f} time {:.2f}".\ + format(bucket_local, float(bucket_local)/float(len(each_bin)),\ + time.time() - start_time_local), flush=True) + + if len(each_bin[bucket_id]) <= 1: + continue + + bucket_urls = each_bin[bucket_id].copy() + remove_urls_list_sub, deduped_local_sub, counter_local_sub = \ + url_pairs_to_remove(args, bucket_urls, url_doc) + + deduped_local += deduped_local_sub + counter_local += counter_local_sub + if len(remove_urls_list_sub) > 0: + remove_urls_list.extend(remove_urls_list_sub) + + return remove_urls_list, deduped_local, counter_local + +def find_pair_urls_parallel(args, lshcache, url_doc): + start_time = time.time() + f_out = open(args.output, 'wb') + deduped, counter = 0, 0 + + # compute jaccards of buckets in bin in parallel (parallelism + # limited to # of bins) + num_bins = len(lshcache.bins) + pool = multiprocessing.Pool(num_bins) + compute_jaccard_partial = partial(compute_jaccard, num_bins=num_bins, \ + start_time_local=start_time) + # don't need to pass args and url_doc as they are already shared + compute_jaccard_iter = pool.imap(compute_jaccard_partial, lshcache.bins) + + print("multiprocessing init took {:.2f}".format(time.time() - start_time),\ + flush=True) + for remove_urls_list, deduped_local, counter_local in compute_jaccard_iter: + deduped += deduped_local + counter += counter_local + write_remove_urls_list(remove_urls_list, f_out) + print(' [write]> processed {} documents in {:.2f} ' + 'seoncds and deduped {} documents ...'.format(counter, time.time()\ + - start_time, deduped), flush=True) + + pool.close() + pool.join() + f_out.close() + + print(' Taken time for jaccard similariries {:.2f} seconds'.format(\ + time.time() - start_time), flush=True) + +def find_pair_urls_sequential(args, lshcache, url_doc): + start_time = time.time() + f_out = open(args.output, 'wb') + deduped, counter = 0, 0 + for b in lshcache.bins: + for bucket_id in b: + if len(b[bucket_id]) <= 1: + continue + + bucket_urls = b[bucket_id].copy() + remove_urls_list_sub, deduped_local_sub, counter_local_sub = \ + url_pairs_to_remove(args, bucket_urls, url_doc) + + deduped += deduped_local_sub + counter += counter_local_sub + write_remove_urls_list(remove_urls_list_sub, f_out) + if counter % 10000 == 0: + print(' [write]> processed {} documents in {:.2f} ' + 'seoncds and deduped {} documents ...'. + format(counter, time.time() - start_time, + deduped), flush=True) + f_out.close() + print(' [write]> processed {} documents in {:.2f} ' + 'seoncds and deduped {} documents ...'. + format(counter, time.time() - start_time, + deduped), flush=True) + +if __name__ == '__main__': + + print('parsing the arguments ...') + + parser = argparse.ArgumentParser() + parser.add_argument('--seed', type=int, default=1234, + help='Random seed used for python, numpy') + parser.add_argument('--inputs', nargs = '*', default=None, help = \ + 'Pairwise list of the input files and keys, ' + 'e.g. --inputs cc.json cc_id news.json news_id') + parser.add_argument('--load-fingerprints', nargs = '*', default=None, + help='Load fingerprints from a list of pickle files,' + ' e.g. cc.pkl news.pkl') + parser.add_argument('--save-fingerprints', type=str, default=None, + help='Save the fingerprints of the inputs.') + parser.add_argument('--output', type=str, default=None, + help='Output file name that consists of all ids' + ' with matching similarities') + parser.add_argument('--jaccard', type=str, default='union', + choices=['union', 'min', 'max'], help='Jaccard'\ + ' similarity computation') + parser.add_argument('--heuristic-iter', type=int, default=1, + help='Number of iterations to run the heuristics' + ': use -1 for exact') + parser.add_argument('--num-bands', type=int, default=10, + help='Number of bands to use in cache') + parser.add_argument('--num-seeds', type=int, default=100, + help='Number of seeds to use for minhash. Note that' + ' this value should be divisible by num-bands') + parser.add_argument('--jaccard-parallel', action='store_true', + help='Use this to process large number of documents.') + args = parser.parse_args() + + print('finding possible duplicate content ...') + + # set seed and get an array of seeds of 100 integers + np.random.seed(args.seed) + seeds = np.random.randint(0, 1e6, size=args.num_seeds) + + # initialize minhash and lsh cache + hasher = minhash.MinHasher(seeds=seeds, char_ngram=5, hashbytes=4) + lshcache = cache.Cache(num_bands=args.num_bands, hasher=hasher) + + url_doc = {} + + # load fingerprints from pickle file if needed + if args.load_fingerprints is not None: + for count_fp, fp_file_name in enumerate(args.load_fingerprints): + print("Loading fingerprints from pickle file {}".format( + fp_file_name), flush=True) + fp = open(fp_file_name, "rb") + if count_fp == 0: + # assign directory for the first pkl + lshcache = pickle.load(fp) + url_doc = pickle.load(fp) + else: + # append these to lshcache and url_doc + local_lshcache = pickle.load(fp) + local_url_doc = pickle.load(fp) + for url in local_lshcache.fingerprints.keys(): + url_doc[url] = local_url_doc[url] + lshcache.add_fingerprint(local_lshcache.fingerprints[url], url) + fp.close() + + counter = 0 + start_time = time.time() + + # compute finger prints of the inputs if any + # input file and the key to use as id + if args.inputs is not None: + print("Computing fingerprints", flush=True) + assert len(args.inputs) % 2 == 0 + for input_file, key in zip(args.inputs[::2], args.inputs[1::2]): + print(' document processing {} with key {}'.format(input_file, key), + flush=True) + + # compute fingerprints in parallel + num_workers = 40 + pool = multiprocessing.Pool(num_workers) + fin = open(input_file, 'r', encoding='utf-8') + compute_fingerprint_partial = partial(compute_fingerprint, key=key) + compute_fingerprint_iter = pool.imap(compute_fingerprint_partial, + fin, 512) + # traverse all the texts and add fingerprints + for url, text, fingerprint, flag in compute_fingerprint_iter: + counter += 1 + if flag: + url_doc[url] = text + lshcache.add_fingerprint(fingerprint, url) + if counter % 10000 == 0: + print(' [read]> processed {} documents in {:.2f} ' + 'seconds ...'.format(counter, time.time() - \ + start_time), flush=True) + + fin.close() + pool.close() + pool.join() + + # Save the fingerprints if needed + if args.save_fingerprints is not None: + print("Saving fingerprints to pickle file {}".format( + args.save_fingerprints), flush=True) + with open(args.save_fingerprints, 'wb') as f_save: + pickle.dump(lshcache, f_save) + pickle.dump(url_doc, f_save) + + # compute jaccard index of the input texts and write to file if needed + if args.output is not None: + print("Compute jaccard similarity", flush=True) + if args.jaccard_parallel: + find_pair_urls_parallel(args, lshcache, url_doc) + else: + find_pair_urls_sequential(args, lshcache, url_doc) + + print('done :-)') + diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/openwebtext/group_duplicate_url.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/openwebtext/group_duplicate_url.py new file mode 100644 index 0000000000000000000000000000000000000000..12dcea60f1214a61e666502a872c630bc9f3ce7a --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/openwebtext/group_duplicate_url.py @@ -0,0 +1,90 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed 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 json +import time +import sys + + +if __name__ == '__main__': + + + print('grouping duplicate urls ...') + + input = sys.argv[1] + output = sys.argv[2] + if len(sys.argv) > 3: + jaccard_similarity_threshold = float(sys.argv[3]) + else: + jaccard_similarity_threshold = 0.7 + + url_to_index = {} + index_to_urls = [] + counter = 0 + start_time = time.time() + with open(input, 'r') as f: + for line in f: + counter += 1 + myjson = json.loads(line) + urls = [] + for main_url in myjson.keys(): + urls.append(main_url) + for value in myjson[main_url]: + for other_url, js in value.items(): + if js >= jaccard_similarity_threshold: + urls.append(other_url) + current_index = -1 + other_indices = set() + for url in urls: + if url in url_to_index: + if current_index == -1: + current_index = url_to_index[url] + elif current_index != url_to_index[url]: + other_indices.add(url_to_index[url]) + if current_index == -1: + current_index = len(index_to_urls) + index_to_urls.append(set()) + for url in urls: + url_to_index[url] = current_index + index_to_urls[current_index].add(url) + for index in other_indices: + for url in index_to_urls[index]: + index_to_urls[current_index].add(url) + url_to_index[url] = current_index + index_to_urls[index] = None + + if counter % 100000 == 0: + print(' > processed {} lines in {} seconds ...'.format( + counter, time.time() - start_time)) + + + total_remove = 0 + total_remain = 0 + for urls in index_to_urls: + if urls is not None: + if len(urls) > 1: + total_remove += (len(urls) - 1) + total_remain += 1 + print('out of {} urls, only {} are unique and {} should be removed'.format( + total_remove+total_remain, total_remain, total_remove)) + + with open(output, 'wb') as f: + for i, urls in enumerate(index_to_urls): + if urls is not None: + if len(urls) > 1: + myjson = json.dumps({str(i): list(urls)}, + ensure_ascii=False) + f.write(myjson.encode('utf-8')) + f.write('\n'.encode('utf-8')) diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/openwebtext/remove_group_duplicates.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/openwebtext/remove_group_duplicates.py new file mode 100644 index 0000000000000000000000000000000000000000..b6f580ef1f5b5e7e56bc11bf982e57dcfb10de3d --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/openwebtext/remove_group_duplicates.py @@ -0,0 +1,69 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed 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 json +import time +import sys + + +if __name__ == '__main__': + + url_filename = sys.argv[1] + data_filename = sys.argv[2] + output_filename = sys.argv[3] + + urls = set() + with open(url_filename, 'r') as f: + for line in f: + myjson = json.loads(line) + for key in myjson: + this_urls = myjson[key] + for i in range(1, len(this_urls)): + urls.add(this_urls[i]) + print('will be removing {} urls'.format(len(urls)), flush=True) + + written_docs = 0 + removed_docs = 0 + removed_chars = 0 + start_time = time.time() + with open(output_filename, 'wb') as fout: + with open(data_filename, 'r') as fin: + for line in fin: + try: + myjson = json.loads(line) + url = myjson['url'] + if url in urls: + print('removing', myjson) + removed_docs += 1 + removed_chars += len(myjson['text']) + continue + myjson = json.dumps(myjson, ensure_ascii=False) + fout.write(myjson.encode('utf-8')) + fout.write('\n'.encode('utf-8')) + written_docs += 1 + if written_docs % 10000 == 0: + print(' [PROCESSED] time (s): {:.2f} | written: {} ' + '| removed: {} (char: {})'.format( + time.time() - start_time, + written_docs, removed_docs, removed_chars)) + except Exception as e: + print('[SKIPPING]', line, e) + + print(' [PROCESSED] time (s): {:.2f} | written: {} ' + '| removed: {} (char: {})'.format( + time.time() - start_time, + written_docs, removed_docs, removed_chars)) + print('done :-)') diff --git a/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/preprocess_data.py b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/preprocess_data.py new file mode 100644 index 0000000000000000000000000000000000000000..c9ecb6af21c8dbc1c27857a687eed5544b6b371a --- /dev/null +++ b/docker/bloom13b/Model-References/MLPERF3.1/Training/benchmarks/gpt3/tools/preprocess_data.py @@ -0,0 +1,203 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed 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. + +"""Processing data for pretraining.""" + +import argparse +import json +import multiprocessing +import os +import sys +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), + os.path.pardir))) +import time + +import torch +try: + import nltk + nltk_available = True +except ImportError: + nltk_available = False + +from megatron.tokenizer import build_tokenizer +from megatron.data import indexed_dataset + + +# https://stackoverflow.com/questions/33139531/preserve-empty-lines-with-nltks-punkt-tokenizer +class CustomLanguageVars(nltk.tokenize.punkt.PunktLanguageVars): + + _period_context_fmt = r""" + \S* # some word material + %(SentEndChars)s # a potential sentence ending + \s* # <-- THIS is what I changed + (?=(?P + %(NonWord)s # either other punctuation + | + (?P\S+) # <-- Normally you would have \s+ here + ))""" + +class IdentitySplitter(object): + def tokenize(self, *text): + return text + +class Encoder(object): + def __init__(self, args): + self.args = args + + def initializer(self): + # Use Encoder class as a container for global data + Encoder.tokenizer = build_tokenizer(self.args) + if self.args.split_sentences: + if not nltk_available: + print("NLTK is not available to split sentences.") + exit() + splitter = nltk.load("tokenizers/punkt/english.pickle") + if self.args.keep_newlines: + # this prevents punkt from eating newlines after sentences + Encoder.splitter = nltk.tokenize.punkt.PunktSentenceTokenizer( + train_text = splitter._params, + lang_vars = CustomLanguageVars()) + else: + Encoder.splitter = splitter + + else: + Encoder.splitter = IdentitySplitter() + + def encode(self, json_line): + data = json.loads(json_line) + ids = {} + for key in self.args.json_keys: + text = data[key] + doc_ids = [] + for sentence in Encoder.splitter.tokenize(text): + sentence_ids = Encoder.tokenizer.tokenize(sentence) + if len(sentence_ids) > 0: + doc_ids.append(sentence_ids) + if len(doc_ids) > 0 and self.args.append_eod: + doc_ids[-1].append(Encoder.tokenizer.eod) + ids[key] = doc_ids + return ids, len(json_line) + +def get_args(): + parser = argparse.ArgumentParser() + group = parser.add_argument_group(title='input data') + group.add_argument('--input', type=str, required=True, + help='Path to input JSON') + group.add_argument('--json-keys', nargs='+', default=['text'], + help='space separate listed of keys to extract from json') + group.add_argument('--split-sentences', action='store_true', + help='Split documents into sentences.') + group.add_argument('--keep-newlines', action='store_true', + help='Keep newlines between sentences when splitting.') + + group = parser.add_argument_group(title='tokenizer') + group.add_argument('--tokenizer-type', type=str, required=True, + choices=['BertWordPieceLowerCase','BertWordPieceCase', + 'GPT2BPETokenizer'], + help='What type of tokenizer to use.') + group.add_argument('--vocab-file', type=str, default=None, + help='Path to the vocab file') + group.add_argument('--merge-file', type=str, default=None, + help='Path to the BPE merge file (if necessary).') + group.add_argument('--append-eod', action='store_true', + help='Append an token to the end of a document.') + + + group = parser.add_argument_group(title='output data') + group.add_argument('--output-prefix', type=str, required=True, + help='Path to binary output file without suffix') + group.add_argument('--dataset-impl', type=str, default='mmap', + choices=['lazy', 'cached', 'mmap']) + + group = parser.add_argument_group(title='runtime') + group.add_argument('--workers', type=int, default=1, + help='Number of worker processes to launch') + group.add_argument('--log-interval', type=int, default=100, + help='Interval between progress updates') + args = parser.parse_args() + args.keep_empty = False + + if args.tokenizer_type.lower().startswith('bert'): + if not args.split_sentences: + print("Bert tokenizer detected, are you sure you don't want to split sentences?") + + # some default/dummy values for the tokenizer + args.rank = 0 + args.make_vocab_size_divisible_by = 128 + args.tensor_model_parallel_size = 1 + args.vocab_extra_ids = 0 + + return args + +def main(): + args = get_args() + startup_start = time.time() + + print("Opening", args.input) + fin = open(args.input, 'r', encoding='utf-8') + + if nltk_available and args.split_sentences: + nltk.download("punkt", quiet=True) + + encoder = Encoder(args) + tokenizer = build_tokenizer(args) + pool = multiprocessing.Pool(args.workers, initializer=encoder.initializer) + encoded_docs = pool.imap(encoder.encode, fin, 25) + #encoded_docs = map(encoder.encode, fin) + + level = "document" + if args.split_sentences: + level = "sentence" + + print(f"Vocab size: {tokenizer.vocab_size}") + print(f"Output prefix: {args.output_prefix}") + output_bin_files = {} + output_idx_files = {} + builders = {} + for key in args.json_keys: + output_bin_files[key] = "{}_{}_{}.bin".format(args.output_prefix, + key, level) + output_idx_files[key] = "{}_{}_{}.idx".format(args.output_prefix, + key, level) + builders[key] = indexed_dataset.make_builder(output_bin_files[key], + impl=args.dataset_impl, + vocab_size=tokenizer.vocab_size) + + startup_end = time.time() + proc_start = time.time() + total_bytes_processed = 0 + print("Time to startup:", startup_end - startup_start) + + for i, (doc, bytes_processed) in enumerate(encoded_docs, start=1): + total_bytes_processed += bytes_processed + for key, sentences in doc.items(): + if len(sentences) == 0: + continue + for sentence in sentences: + builders[key].add_item(torch.IntTensor(sentence)) + builders[key].end_document() + if i % args.log_interval == 0: + current = time.time() + elapsed = current - proc_start + mbs = total_bytes_processed/elapsed/1024/1024 + print(f"Processed {i} documents", + f"({i/elapsed} docs/s, {mbs} MB/s).", + file=sys.stderr) + + for key in args.json_keys: + builders[key].finalize(output_idx_files[key]) + +if __name__ == '__main__': + main()