diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/dataset/README.md b/docker/intel_code/llama13b/Megatron-DeepSpeed/dataset/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1f0aa31d96f2126b7ddc201385c266bca2f122cc --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/dataset/README.md @@ -0,0 +1,5 @@ +# Run the scripts below to setup dataset + +bash download_books.sh + +bash download_vocab.sh diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/dataset/download_books.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/dataset/download_books.sh new file mode 100644 index 0000000000000000000000000000000000000000..cb93c2b21328886ec4b425fdcf788011d913fa57 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/dataset/download_books.sh @@ -0,0 +1,2 @@ +wget https://the-eye.eu/public/AI/pile_neox/data/BookCorpusDataset_text_document.bin +wget https://the-eye.eu/public/AI/pile_neox/data/BookCorpusDataset_text_document.idx \ No newline at end of file diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/dataset/download_ckpt.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/dataset/download_ckpt.sh new file mode 100644 index 0000000000000000000000000000000000000000..ac10274b187057ccda7284a84c55cc63f9d247f2 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/dataset/download_ckpt.sh @@ -0,0 +1,8 @@ +mkdir -p checkpoints/gpt2_345m + +cd checkpoints/gpt2_345m +wget --content-disposition https://api.ngc.nvidia.com/v2/models/nvidia/megatron_lm_345m/versions/v0.0/zip -O megatron_lm_345m_v0.0.zip +unzip megatron_lm_345m_v0.0.zip +rm megatron_lm_345m_v0.0.zip +cd ../.. + diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/dataset/download_vocab.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/dataset/download_vocab.sh new file mode 100644 index 0000000000000000000000000000000000000000..0b7637104baaa0f1d413d03143b20f17b0a1ad40 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/dataset/download_vocab.sh @@ -0,0 +1,2 @@ +wget https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-vocab.json +wget https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-merges.txt \ No newline at end of file diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_config_gpt_TEMPLATE.json b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_config_gpt_TEMPLATE.json new file mode 100644 index 0000000000000000000000000000000000000000..5a14931cb99d667078a36ffac07b7b8ff9a470e6 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_config_gpt_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": ZERO_STAGE + }, + + "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/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_config_gpt_Zero2_TEMPLATE.json b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_config_gpt_Zero2_TEMPLATE.json new file mode 100644 index 0000000000000000000000000000000000000000..4d0a68f72deb3930c85adb69f37b331a706f6b22 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/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/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_evalharness.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_evalharness.sh new file mode 100644 index 0000000000000000000000000000000000000000..3496ada20d13c98845686c1c847a536bb3203a39 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_evalharness.sh @@ -0,0 +1,72 @@ +# 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 \ + --tokenizer-type GPT2BPETokenizer \ + --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/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_1.3B_MoE128.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_1.3B_MoE128.sh new file mode 100644 index 0000000000000000000000000000000000000000..0f2805dfd0fe501a4081fd4a2f8c9e83e298f223 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_1.3B_MoE128.sh @@ -0,0 +1,348 @@ +#!/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 +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-opt_param-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/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_1.3B_PR-MoE64or128.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_1.3B_PR-MoE64or128.sh new file mode 100644 index 0000000000000000000000000000000000000000..f758ac69bf3bff404e63d019a07c9722360b1241 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_1.3B_PR-MoE64or128.sh @@ -0,0 +1,340 @@ +#!/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 +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-opt_param-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/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_1.3B_PR-MoE64or128_MoS.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_1.3B_PR-MoE64or128_MoS.sh new file mode 100644 index 0000000000000000000000000000000000000000..34bc60548f3591130409c2cdb27eef33a96a14af --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_1.3B_PR-MoE64or128_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 +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-opt_param-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/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_1.3B_dense.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_1.3B_dense.sh new file mode 100644 index 0000000000000000000000000000000000000000..27b546435abda16cb554da0a215ba87ba4921646 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_1.3B_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=2 + +## Model parallelism, 1 is no MP +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-opt_param-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/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_1.3B_dense_cl.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_1.3B_dense_cl.sh new file mode 100644 index 0000000000000000000000000000000000000000..e40b55b80969698e952a05897dc0c728488fb1e2 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/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-opt_param-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/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_125M_MoE64.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_125M_MoE64.sh new file mode 100644 index 0000000000000000000000000000000000000000..f93f0b71268fcd7bd2535df9ff19c3a862969adf --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_125M_MoE64.sh @@ -0,0 +1,372 @@ +#!/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 +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-opt_param-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/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_125M_dense_cl.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_125M_dense_cl.sh new file mode 100644 index 0000000000000000000000000000000000000000..36b654e02b91a0227afec91b6655b63bbde61c1b --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/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-opt_param-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/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_350M_MoE128.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_350M_MoE128.sh new file mode 100644 index 0000000000000000000000000000000000000000..4f8007b01e33fa862f8a6574002cc2012729d575 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_350M_MoE128.sh @@ -0,0 +1,348 @@ +#!/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 +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-opt_param-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/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_350M_PR-MoE32or64.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_350M_PR-MoE32or64.sh new file mode 100644 index 0000000000000000000000000000000000000000..d9f8513809f6e99deca59f1f90b4d412b9a0e446 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_350M_PR-MoE32or64.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=4 + +## Model parallelism, 1 is no MP +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-opt_param-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/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_350M_PR-MoE32or64_MoS.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_350M_PR-MoE32or64_MoS.sh new file mode 100644 index 0000000000000000000000000000000000000000..a5b349b9e7fde267f39064bf072d4635057e2247 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_350M_PR-MoE32or64_MoS.sh @@ -0,0 +1,353 @@ +#!/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 +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-opt_param-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/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_350M_dense.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_350M_dense.sh new file mode 100644 index 0000000000000000000000000000000000000000..405817a06e1b2da699057acc1cd4075e5121a29d --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_350M_dense.sh @@ -0,0 +1,348 @@ +#!/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 +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-opt_param-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/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_6.7B_dense.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_6.7B_dense.sh new file mode 100644 index 0000000000000000000000000000000000000000..1fdd76cbe335a4f99512a756ee2993fe9873e441 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/MoE/ds_pretrain_gpt_6.7B_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 +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-opt_param-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/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/README.md b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3d899816640af41aceeb18a0b6c43532bfcc77c8 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/README.md @@ -0,0 +1,33 @@ +# Megatron-DeepSpeed Recipes and Scripts + +This folder includes various example scripts with DeepSpeed technologies integrated. Below we describe each sub-folder, sorted by last update date. + +## Sync with NVIDIA/Megatron-LM (last updated: Jul 2023) +The ```rebase``` folder includes details about the recent sync with the NVIDIA/Megatron-LM repo (where this repo is forked from). It includes example scripts we used to test after the sync, together with a README documentation about what were tested. + +## Data Efficiency (last updated: Feb 2023) + +The ```data_efficiency``` folder includes GPT-3 and BERT pretraining examples for DeepSpeed Data Efficiency Library, together with examples of zero-shot evaluation for GPT models and GLUE finetuning for BERT models. Please refer to the detailed tutorials in data_efficiency/README.MD. Currently this folder includes the newest example scripts for GPT/BERT pretraining/eval/finetuning, both with and without DeepSpeed Data Efficiency Library techniques. + +## BERT example (last updated: Dec 2022) + +The ```bert_with_pile``` folder includes examples about BERT-style model pre-training (using the public Pile data or user's own data) with DeepSpeed integration. Please refer to the readme in the folder for tutorial. + +## Azure (last updated: Nov 2022) + +We strongly recommend to start with AzureML recipe in the ```azureml``` folder. + +If you have a custom infrastructure (e.g. HPC clusters) or Azure VM and VMSS based environments, please refer to the bash scripts in the ```azure``` folder. + +## Model Compression (last updated: Aug 2022) + +The ```compression``` folder includes examples about layer reduction for task-agnostic compression. Please refer to [this tutorial](https://www.deepspeed.ai/tutorials/model-compression/#11-layer-reduction) about the DeepSpeed Model Compression Library. These recipes are for GPT-style NLG models. + +## MoE (last updated: Jun 2022) + +Please see the ```MoE``` folder for different training recipes and scripts for Mixture-of-expert based models and dense models. These recipes are for GPT-style NLG models, and currently this is the only folder with MoE training examples. + +## Curriculum Learning (last updated: Oct 2021) + +Curriculum learning recipes are in the ```curriculum_learning``` folder. Please refer to the detailed tutorials linked inside. These recipes are for GPT-style NLG models. +Note that the DeepSpeed Data Efficiency Library above includes a more general curriculum learning support. This legacy curriculum learning feature is still compatible, but we recommend using the DeepSpeed Data Efficiency Library above. However, the newer DeepSpeed Data Efficiency Library currently is not compatible with pipeline parallelism. So if you have to use pipeline parallelism, you would need to use this legacy curriculum learning version. diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/curriculum_learning/README.md b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/curriculum_learning/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a80e3510cc7c2c4435c5fadc98c1e7dd17239d20 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/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/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/curriculum_learning/ds_pretrain_gpt2.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/curriculum_learning/ds_pretrain_gpt2.sh new file mode 100644 index 0000000000000000000000000000000000000000..96a6186661a06bbdeef3813a735d5219b9b27db7 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/curriculum_learning/ds_pretrain_gpt2.sh @@ -0,0 +1,150 @@ +#! /bin/bash + +CONFIG=$1 +TAG=$2 +MODEL_SIZE=$3 +LR=$4 +TOTAL_BATCHSIZE=$5 +SEQ_LEN=$6 +MP_SIZE=$7 +SEED=$8 +SAVE_INTERVAL=$9 +NUM_ITER=${10} +NUM_TOKEN=${11} +LR_DECAY_TOKEN=${12} +LR_WARMUP_ITER=${13} +CONFIG_TEMPLATE=${14} +CURRICULUM_STEP=${15} +CURRICULUM_MIN=${16} + +# 12-layer, 768-hidden, 12-heads, 117M parameters +# 24-layer, 1024-hidden, 16-heads, 345M parameters +# 36-layer, 1280-hidden, 20-heads, 774M parameters +# 48-layer, 1600-hidden, 25-heads, 1558M parameters +if [[ $MODEL_SIZE -eq 117 ]]; then + NUM_LAYERS=12 + HIDDEN_SIZE=768 + NUM_ATTN_HEADS=12 +elif [[ $MODEL_SIZE -eq 345 ]]; then + NUM_LAYERS=24 + HIDDEN_SIZE=1024 + NUM_ATTN_HEADS=16 +elif [[ $MODEL_SIZE -eq 774 ]]; then + NUM_LAYERS=36 + HIDDEN_SIZE=1280 + NUM_ATTN_HEADS=20 +elif [[ $MODEL_SIZE -eq 1558 ]]; then + NUM_LAYERS=48 + HIDDEN_SIZE=1600 + NUM_ATTN_HEADS=25 +else + echo "Model size not supported." + exit 1 +fi + +# Pipeline parallelism. 1 means no pipelines. +PP_SIZE=1 + +# Change for multinode config +NUM_WORKERS=16 +NUM_GPUS_PER_WORKER=8 +NUM_GPUS=$(( ${NUM_WORKERS} * ${NUM_GPUS_PER_WORKER} )) +if [[ $PP_SIZE -gt 0 ]]; then + DP_SIZE=$(( ${NUM_GPUS} / (${PP_SIZE} * ${MP_SIZE}) )) +else + DP_SIZE=$(( ${NUM_GPUS} / ${MP_SIZE} )) +fi +# Batch size per gpu, here we assume grad accumulation step 1 +# you can reduce this if gpu OOM +BATCHSIZE=$((TOTAL_BATCHSIZE/DP_SIZE)) + +DATA_PATH=/vc_data/Megatron-LM/data/indexed_datasets/megatron +VOCAB_PATH=/vc_data/Megatron-LM/data/gpt2-vocab.json +MERGE_PATH=/vc_data/Megatron-LM/data/gpt2-merges.txt + +#ZeRO Configs +stage=1 + +current_time=$(date "+%Y.%m.%d-%H.%M.%S") +script_path=$(realpath $0) +script_dir=$(dirname $script_path) +host="${HOSTNAME}" + +if [ "${CONFIG_TEMPLATE}" = "true" ]; then +template_json="$script_dir/ds_zero_stage_${stage}_config_${CONFIG}.json" +config_json="$script_dir/ds_zero_stage_${stage}_config_${CONFIG}_min${CURRICULUM_MIN}_max${SEQ_LEN}_step${CURRICULUM_STEP}.json" +sed "s/CONFIG_CL_MIN/${CURRICULUM_MIN}/" ${template_json} \ + | sed "s/CONFIG_CL_MAX/${SEQ_LEN}/" \ + | sed "s/CONFIG_CL_DURATION/${CURRICULUM_STEP}/" \ + > ${config_json} +else +config_json="$script_dir/ds_zero_stage_${stage}_config_${CONFIG}.json" +fi + +JOB_NAME="gpt2_${MODEL_SIZE}M_bsz${TOTAL_BATCHSIZE}_seq${SEQ_LEN}_lr${LR}_warmup${LR_WARMUP_ITER}_decay${LR_DECAY_TOKEN}_seed${SEED}_${TAG}_stage${stage}_n${NUM_WORKERS}_g${NUM_GPUS_PER_WORKER}_mp${MP_SIZE}" +LOG_NAME="${JOB_NAME}_${host}_${current_time}" + +OUTPUT_BASEPATH="/vc_data_blob/users/conglli" +mkdir -p "${OUTPUT_BASEPATH}/tensorboard/curriculum/" +mkdir -p "${OUTPUT_BASEPATH}/checkpoint/curriculum/" +mkdir -p "${OUTPUT_BASEPATH}/log/curriculum/" +LOGDIR="${OUTPUT_BASEPATH}/tensorboard/curriculum/${LOG_NAME}" +CHECKPOINT_PATH="${OUTPUT_BASEPATH}/checkpoint/curriculum/${JOB_NAME}" + +gpt_options=" \ + --tensor-model-parallel-size ${MP_SIZE} \ + --num-layers $NUM_LAYERS \ + --hidden-size $HIDDEN_SIZE \ + --num-attention-heads $NUM_ATTN_HEADS \ + --seq-length $SEQ_LEN \ + --max-position-embeddings $SEQ_LEN \ + --micro-batch-size $BATCHSIZE \ + --global-batch-size ${TOTAL_BATCHSIZE} \ + --train-iters $NUM_ITER \ + --train-tokens $NUM_TOKEN \ + --lr-decay-tokens $LR_DECAY_TOKEN \ + --save $CHECKPOINT_PATH \ + --load $CHECKPOINT_PATH \ + --data-path $DATA_PATH \ + --vocab-file $VOCAB_PATH \ + --merge-file $MERGE_PATH \ + --data-impl mmap \ + --split 949,50,1 \ + --distributed-backend nccl \ + --override-opt_param-scheduler \ + --lr $LR \ + --lr-decay-style cosine \ + --min-lr 1.0e-5 \ + --weight-decay 1e-2 \ + --clip-grad 1.0 \ + --lr-warmup-iters $LR_WARMUP_ITER \ + --checkpoint-activations \ + --log-interval 100 \ + --save-interval $SAVE_INTERVAL \ + --eval-interval 100 \ + --eval-iters 10 \ + --fp16 \ + --seed $SEED \ + --tensorboard-queue-size 1 \ + --log-timers-to-tensorboard \ + --log-batch-size-to-tensorboard \ + --log-validation-ppl-to-tensorboard \ + --no-masked-softmax-fusion \ + --tensorboard-dir ${LOGDIR} +" + +deepspeed_options=" \ + --deepspeed \ + --deepspeed_config ${config_json} \ + --zero-stage ${stage} \ + --pipeline-model-parallel-size ${PP_SIZE} \ + --deepspeed-activation-checkpointing +" + +full_options="${gpt_options} ${deepspeed_options}" + +run_cmd="deepspeed --num_nodes ${NUM_WORKERS} --num_gpus ${NUM_GPUS_PER_WORKER} ../../pretrain_gpt.py ${full_options} &>> ${OUTPUT_BASEPATH}/log/curriculum/${JOB_NAME}.log" +echo ${run_cmd} +eval ${run_cmd} + +set +x diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/curriculum_learning/ds_pretrain_gpt_1.3B_rope_slw.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/curriculum_learning/ds_pretrain_gpt_1.3B_rope_slw.sh new file mode 100644 index 0000000000000000000000000000000000000000..209021a39273fcdd2e421da4e694ffed53de5c72 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/curriculum_learning/ds_pretrain_gpt_1.3B_rope_slw.sh @@ -0,0 +1,347 @@ +#!/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 + +## init_std is 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) + +## We changed min_lr to a lower number (1.0e-6), which we found is able to +## provide better zero-shot eval results. + +## 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=1.0e-6 +# init_std=0.02 + +## 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=1.0e-6 +# init_std=0.018 + +## 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=1.0e-6 +# init_std=0.015 + +## 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=1.0e-6 +init_std=0.013 + +## 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.0e-6 +# init_std=0.011 + +## 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.0e-6 +# init_std=0.009 + +## 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-6 +# init_std=0.008 + +## 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=1.0e-6 +# init_std=0.005 +############################################################################### +### Training duration configs +## The main termination condition, original GPT-3 paper trains for 300B tokens. +train_tokens_in_billion=300 +train_tokens=$((${train_tokens_in_billion} * 1000000000)) + +## 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 data efficiency techniques may change num tokens 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=$(( 300 * 1000000000 * 2 / ${seq_len} )) + +## Another wall-clock time termination condition in minutes. Set it large +## enough to avoid undesired early termination. +exit_duration=30000000 +############################################################################### +### lr configs +## lr warmup and decay duration. +## Original GPT-3 paper uses 375M warmup tokens and 260B cosine decay tokens. +## Here we increase the warmup tokens to 3B since when batch size warmup is not +## used, there are more tokens per step. Thus we need to increase warmup tokens +## to make sure there are enough warmup steps, which is important for training +## stability. +lr_warmup_tokens_in_million=3000 +lr_warmup_tokens=$((${lr_warmup_tokens_in_million} * 1000000)) +## Here we changed the LR decay tokens to align with total train tokens, since +## related works (e.g., https://arxiv.org/abs/2203.15556) find that setting the +## learning rate schedule to match the number of training tokens results in the +## best final model quality +lr_decay_tokens_in_billion=${train_tokens_in_billion} +lr_decay_tokens=$((${lr_decay_tokens_in_billion} * 1000000000)) +lr_decay_style="cosine" +############################################################################### +### Parallelism configs +## Model parallelism, 1 is no MP +mp_size=4 + +## Pipeline parallelism. To disable PP, set pp_size to 1 and no_pp to true. +## Note that currently both curriculum learning and random-LTD are NOT +## compatible with pipeline parallelism. +pp_size=8 +no_pp="false" + +## ZeRO-based data parallelism, stage=0 will disable ZeRO +zero_stage=1 + +## Total number of GPUs. ds_ssh is from DeepSpeed library. +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} )) + +## Data parallel size. +dp_size=$(( ${num_gpus} / ${pp_size} / ${mp_size} )) + +## Micro batch size per GPU +## Make sure that batch_size <= global_batch_size*pp_size*mp_size/num_gpus +## Reduce it manually if GPU OOM +# batch_size=$(( ${global_batch_size} / ${dp_size} )) +batch_size=2 +############################################################################### +### curriculum learning (sequence length warmup) configs +# The "divided by 3" means we use 1/3 of baseline's total steps for sequence length warmup. +# This is not always the best config, but usually a reasonable choice to start with. +cl_step=$(( ${lr_warmup_tokens} / 3 / ${global_batch_size} / ${seq_len} )) +# Starting sequence length during sequence length warmup. If the train/validation loss is +# unstable at the beginning of training, need to increase this but also need to keep as multiples +# of 8 in order to enable Tensor Core acceleration. +cl_min=64 +############################################################################### +### Misc configs +log_interval=10 +eval_iters=10 +eval_interval=100 +# num_save controls how frequent to save checkpoint. num_save=20 means that a +# checkpoint will be saved every 5% of training. For longer training you would +# want larger num_save to save more frequently, and vice versa. +num_save=100 +estimated_train_iter=$((${train_tokens} / ${seq_len} / ${global_batch_size})) +# save_interval=$((${estimated_train_iter} / ${num_save})) +save_interval=100 + +## 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}" +seed=1234 +num_workers=0 + +## Public the Pile dataset, can be downloaded at +## https://mystic.the-eye.eu/public/AI/pile_neox/ or +## https://the-eye.eu/public/AI/pile_neox/ Change data_home to where you +## store the pile_text_document.bin and pile_text_document.idx. +data_home="/vc_data_blob/users/conglli/the_pile_public_merged_nopreprocessing" +data_path="${data_home}/pile_text_document" + +vocab_path="gpt2-vocab.json" +if [ ! -f "$vocab_path" ]; then + wget https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-vocab.json +fi +merge_path="gpt2-merges.txt" +if [ ! -f "$merge_path" ]; then + wget https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-merges.txt +fi + +prescale_grad="true" +jobname="gpt_${model_size}B_tok${train_tokens_in_billion}B" +jobname="${jobname}_lr${lr}_min${min_lr}_w${lr_warmup_tokens_in_million}M_d${lr_decay_tokens_in_billion}B_${lr_decay_style}" +jobname="${jobname}_gbs${global_batch_size}_mbs${batch_size}_g${num_gpus}" +if [[ $zero_stage -gt 0 ]]; then + jobname="${jobname}_z${zero_stage}" + prescale_grad="false" +fi +if [[ $mp_size -gt 1 ]]; then + jobname="${jobname}_mp${mp_size}" +fi +if [ "${no_pp}" = "false" ]; then + jobname="${jobname}_pp${pp_size}" +fi +jobname="${jobname}_seed${seed}_rebase_rope0.25" +jobname="${jobname}_cl_step${cl_step}_cl_min${cl_min}" + +username=$(whoami) +output_home="/blob/users/${username}/project/data_efficient_gpt" +log_path="${output_home}/log/" +checkpoint_path="${output_home}/checkpoint/${jobname}" +## Microsoft internal constraint: because tensorboard is logged by last rank, +## it's better to put the path in NFS instead of Blob. +tensorboard_dir="/vc_data/users/${username}/project/data_efficient_gpt/tensorboard/" +tensorboard_path="${tensorboard_dir}${jobname}_${host}_${current_time}" +mkdir -p ${log_path} +mkdir -p ${checkpoint_path} +mkdir -p ${tensorboard_path} +############################################################################### +data_options=" \ + --vocab-file ${vocab_path} \ + --merge-file ${merge_path} \ + --data-path ${data_path} \ + --data-impl mmap" + +## If CL is used, make sure to set "--split" the same as what you used during +## offline data analysis&indexing. +megatron_options=" \ + --override-opt_param-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 ${lr_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 ${lr_decay_style} \ + --split 949,50,1 \ + --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 ${num_workers} \ + --fp16 \ + --seed ${seed} \ + --load ${checkpoint_path} \ + --save ${checkpoint_path} \ + --no-async-tensor-model-parallel-allreduce \ + --use-rotary-position-embeddings \ + --rotary-percent 0.25 \ + --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 + +config_json="ds_config_gbs${global_batch_size}_mbs${batch_size}_log${log_interval}_zero${zero_stage}_cl_step${cl_step}_cl_min${cl_min}.json" +template_json="ds_config_gpt_slw_TEMPLATE.json" +sed "s/GBSIZE/${global_batch_size}/" ${template_json} \ + | sed "s/MBSIZE/${batch_size}/" \ + | sed "s/LOG_INTERVAL/${log_interval}/" \ + | sed "s/ZERO_STAGE/${zero_stage}/" \ + | sed "s/PRESCALE_GRAD/${prescale_grad}/" \ + | sed "s/CONFIG_CL_MIN/${cl_min}/" \ + | sed "s/CONFIG_CL_MAX/${seq_len}/" \ + | sed "s/CONFIG_CL_DURATION/${cl_step}/" \ + > ${config_json} + +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 + +deepspeed ${dir}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &>> ${log_path}/${jobname}_${host}_${current_time}.log \ No newline at end of file diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/curriculum_learning/ds_train.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/curriculum_learning/ds_train.sh new file mode 100644 index 0000000000000000000000000000000000000000..aac11ab034bd075dec482d611556f4ee7191c70f --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/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/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/analyze_data.py b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/analyze_data.py new file mode 100644 index 0000000000000000000000000000000000000000..36002d46d1692be0f3d49cc321f6fe15c83154eb --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/analyze_data.py @@ -0,0 +1,239 @@ +# 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. + +''' +Copyright 2022 The Microsoft DeepSpeed Team +''' + +import os +import time +import sys +import math +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), + os.path.pardir,os.path.pardir))) +from datetime import datetime +import numpy as np +import torch + +from deepspeed.runtime.data_pipeline.data_sampling.data_analyzer \ + import DataAnalyzer +from deepspeed.runtime.data_pipeline.data_sampling.indexed_dataset \ + import MMapIndexedDataset + +from megatron import get_args +from megatron import print_rank_0 +from megatron.initialize import initialize_megatron + +def get_tasks_args(parser): + """Provide extra arguments required for data analyzing.""" + group = parser.add_argument_group(title='data_analyzing') + + group.add_argument('--analyzing-task', type=str, required=True, + default=None, + choices=['map', + 'reduce'], + help='What type of analyzing task to perform.') + group.add_argument('--analyzing-data-type', type=str, required=True, + default=None, + choices=['BERT', + 'GPT'], + help='What type of data.') + group.add_argument('--analyzing-metric', type=str, nargs='+', default=[], + help='What kinds of metrics to analyze.') + group.add_argument('--analyzing-num-workers', type=int, default=1, + help='Number of workers. Each worker could be a single CPU node.') + group.add_argument('--analyzing-worker-id', type=int, default=0, + help='Worker id of current node.') + group.add_argument('--analyzing-num-threads', type=int, default=1, + help='Number of threads for each worker.') + group.add_argument('--analyzing-num-threads-reduce', type=int, default=1, + help='Number of threads for each worker.') + group.add_argument('--analyzing-specific-threads', type=int, nargs='+', default=[], + help='Which specific threads to run. Helpful when there are specific thread failed in previous run.') + return parser + +def train_valid_test_datasets_provider_gpt(): + """Build train, valid, and test datasets.""" + args = get_args() + + print_rank_0('> building train, validation, and test datasets ' + 'for GPT ...') + from megatron.data.gpt_dataset import build_train_valid_test_datasets + train_ds, valid_ds, test_ds = build_train_valid_test_datasets( + data_prefix=args.data_path, + data_impl=args.data_impl, + splits_string=args.split, + train_valid_test_num_samples=[1,1,1], # Just dummy numbers since we assume args.train_data_exact_num_epochs will override them + seq_length=args.seq_length, + seed=args.seed, + skip_warmup=(not args.mmap_warmup)) + print_rank_0("> finished creating GPT datasets ...") + + return train_ds, valid_ds, test_ds + +def train_valid_test_datasets_provider_bert(): + """Build train, valid, and test datasets.""" + args = get_args() + + print_rank_0('> building train, validation, and test datasets ' + 'for BERT ...') + from megatron.data.dataset_utils import build_train_valid_test_datasets + train_ds, valid_ds, test_ds = build_train_valid_test_datasets( + data_prefix=args.data_path, + data_impl=args.data_impl, + splits_string=args.split, + train_valid_test_num_samples=[1,1,1], # Just dummy numbers since we assume args.train_data_exact_num_epochs will override them + max_seq_length=args.seq_length, + masked_lm_prob=args.mask_prob, + short_seq_prob=args.short_seq_prob, + seed=args.seed, + skip_warmup=(not args.mmap_warmup), + binary_head=args.bert_binary_head) + print_rank_0("> finished creating BERT datasets ...") + + return train_ds, valid_ds, test_ds + +def metric_seqlen(data): + metric = torch.count_nonzero(data['padding_mask'], dim=1) + return metric + +def metric_total_vocab_freq(data): + args = get_args() + if args.analyzing_data_type == 'BERT': + frequency = torch.bincount(data['text'].view(-1), + minlength=args.padded_vocab_size+1, + weights=data['padding_mask'].view(-1)) + elif args.analyzing_data_type == 'GPT': + frequency = torch.bincount(data['text'].view(-1), + minlength=args.padded_vocab_size+1) + return frequency + +def metric_vocab_rarity(data): + args = get_args() + if args.analyzing_data_type == 'BERT': + rarity = torch.sum(data['padding_mask'] * \ + args.total_vocab_freq[data['text']], dim=1).to(torch.long) + elif args.analyzing_data_type == 'GPT': + rarity = [] + # Do one by one to avoid too high memory consumption + for row in range(data['text'].size()[0]): + rarity.append(int(torch.sum(args.total_vocab_freq[data['text'][row]]).item())) + rarity = torch.tensor(rarity, dtype=torch.long) + print(f"rarity min {min(rarity)}, max {max(rarity)}, len {len(rarity)}, avg {sum(rarity)/len(rarity)}") + return rarity + +def metric_seqlen_vocab_rarity(data): + args = get_args() + metric = torch.count_nonzero(data['padding_mask'], dim=1).to(torch.long) * args.seqlen_coeff + metric += torch.sum(data['padding_mask'] * \ + args.total_vocab_freq[data['text']], dim=1).to(torch.long) + print(f"metric min {min(metric)}, max {max(metric)}, len {len(metric)}, avg {sum(metric)/len(metric)}") + return metric + +def get_metric_function(metric_name): + if metric_name == 'seqlen': + return metric_seqlen + if metric_name == 'total_vocab_freq': + return metric_total_vocab_freq + if metric_name == 'vocab_rarity': + return metric_vocab_rarity + if metric_name == 'seqlen_vocab_rarity': + return metric_seqlen_vocab_rarity + +def get_metric_type(metric_name): + if metric_name == 'seqlen': + return 'single_value_per_sample' + if metric_name == 'total_vocab_freq': + return 'accumulate_value_over_samples' + if metric_name == 'vocab_rarity': + return 'single_value_per_sample' + if metric_name == 'seqlen_vocab_rarity': + return 'single_value_per_sample' + +def run_map(): + args = get_args() + if args.analyzing_data_type == 'BERT': + args.mask_prob = 0 # When analyzing data, we don't want any mask. + train_ds, _, _ = train_valid_test_datasets_provider_bert() + elif args.analyzing_data_type == 'GPT': + train_ds, _, _ = train_valid_test_datasets_provider_gpt() + assert 'seqlen' not in args.analyzing_metric, 'GPT data has fixed seqlen, thus unnecessary to analyze seqlen metric.' + assert 'seqlen_vocab_rarity' not in args.analyzing_metric, 'GPT data has fixed seqlen, thus unnecessary to analyze seqlen metric.' + if 'vocab_rarity' in args.analyzing_metric or 'seqlen_vocab_rarity' in args.analyzing_metric: + total_vocab_freq_fname = f"{args.save}/total_vocab_freq/total_vocab_freq_metric_value" + assert os.path.isfile(f"{total_vocab_freq_fname}.bin") and os.path.isfile(f"{total_vocab_freq_fname}.idx"), "To analyze vocab rarity, first need to analyze the total vocab freq." + total_vocab_freq = MMapIndexedDataset(total_vocab_freq_fname, skip_warmup=True) + total_vocab_freq = np.copy(total_vocab_freq[0]) + total_vocab_freq[total_vocab_freq == 0] = 1 # Avoid log(0) error + total_vocab_freq = np.log(total_vocab_freq/sum(total_vocab_freq)) * -1 + args.total_vocab_freq = torch.tensor(total_vocab_freq, dtype=torch.double) + if 'seqlen_vocab_rarity' in args.analyzing_metric: + # Use large coeff to make seqlen dominates vocab_rarity + max_possible_rarity = args.seq_length * torch.max(args.total_vocab_freq).item() + args.seqlen_coeff = 10 ** (math.ceil(math.log(max_possible_rarity, 10)) + 1) + print(f"Metric seqlen_vocab_rarity: using {args.seqlen_coeff} as coefficient for seqlen.") + metric_functions = [get_metric_function(x) for x in args.analyzing_metric] + metric_types = [get_metric_type(x) for x in args.analyzing_metric] + # For metric_dtypes we int64 by default since it could be hard to estimate + # the appropriate dtype before the mapping analysis. During reduce where + # we merge the analysis results, the DataAnalyzer will automatically choose + # the dtype of merged result file as the smallest one that meet the range + # requirement. + metric_dtypes = [np.int64 for x in args.analyzing_metric] + start = time.time() + data_analyzer = DataAnalyzer(train_ds, + num_workers=args.analyzing_num_workers, + worker_id=args.analyzing_worker_id, + num_threads=args.analyzing_num_threads, + specific_threads=args.analyzing_specific_threads, + batch_size=args.global_batch_size, metric_names=args.analyzing_metric, + metric_functions=metric_functions, metric_types=metric_types, + metric_dtypes=metric_dtypes, save_path=args.save) + data_analyzer.run_map() + duration = (time.time() - start) / 3600.0 + print(f"map job finished in {duration} hr.") + +def run_reduce(): + args = get_args() + if args.analyzing_data_type == 'BERT': + args.mask_prob = 0 # When analyzing data, we don't want any mask. + train_ds, _, _ = train_valid_test_datasets_provider_bert() + elif args.analyzing_data_type == 'GPT': + train_ds, _, _ = train_valid_test_datasets_provider_gpt() + metric_functions = [get_metric_function(x) for x in args.analyzing_metric] + metric_types = [get_metric_type(x) for x in args.analyzing_metric] + metric_dtypes = [np.int64 for x in args.analyzing_metric] + start = time.time() + data_analyzer = DataAnalyzer(train_ds, + num_workers=args.analyzing_num_workers, + num_threads=args.analyzing_num_threads, + num_threads_reduce=args.analyzing_num_threads_reduce, + batch_size=args.global_batch_size, metric_names=args.analyzing_metric, + metric_functions=metric_functions, metric_types=metric_types, + metric_dtypes=metric_dtypes, save_path=args.save) + data_analyzer.run_reduce() + duration = (time.time() - start) / 3600.0 + print(f"reduce job finished in {duration} hr.") + +if __name__ == "__main__": + initialize_megatron(extra_args_provider=get_tasks_args, allow_no_cuda=True) + args = get_args() + if args.analyzing_task == 'map': + run_map() + elif args.analyzing_task == 'reduce': + run_reduce() + else: + raise NotImplementedError('Task {} is not implemented.'.format( + args.analyzing_task)) diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/bert/ds_analyze_bert_data_map.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/bert/ds_analyze_bert_data_map.sh new file mode 100644 index 0000000000000000000000000000000000000000..7f23e361573165df18147626d0e7d31f6b8da7aa --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/bert/ds_analyze_bert_data_map.sh @@ -0,0 +1,67 @@ +#!/bin/bash + +num_workers=1 # Num nodes to run the map job +num_threads=40 # Num threads on each node. Set this based on #CPU cores + +# If different data epochs have slightly different data samples (e.g., due +# to randomness), then you need to specify large enough num_epochs that cover +# whole pretraining. If different data epochs are the same, set num_epochs to +# 1 to only index 1 epoch, and during pretraining DeepSpeed data efficiency +# library will automatically handle reshuffling when reaching another epoch. +num_epochs=5 + +# Which node is this node (start with 0 and end with num_workers-1). This +# script only launch the map job on 1 worker node, since we don't expect +# running on many nodes and workers don't need any communication. But you +# can modify this script to add a MPI/torch distributed launcher. +worker_id=$1 +save_path="/blob/users/conglli/data/analysis_pile_bert_${num_epochs}epoch/" + +metric='total_vocab_freq' +# metric='vocab_rarity' # this requires the result of total_vocab_freq +# metric='seqlen_vocab_rarity' # this requires the result of total_vocab_freq +# metric='seqlen' + +seq_len=512 +batch_size=10000 + +jobname="bert-pile-analyzing-${metric}-${num_epochs}epoch-map-worker${worker_id}" +## Public the Pile dataset, see prepare_pile_data.py in the same directory +## about how to download and preprocess the data. +## Change data_home to your own training data path. +# data_home="/vc_data_blob/users/conglli/the_pile_bert" +data_home="/blob/data/the_pile_bert" +data_path="${data_home}/pile_bert_train_text_sentence" + +vocab_path="bert-large-uncased-vocab.txt" +if [ ! -f "$vocab_path" ]; then + wget https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt +fi + +# Make sure the "--split" is the same as what you will use for pre-training. +options=" \ + --analyzing-task map \ + --analyzing-data-type BERT \ + --analyzing-metric ${metric} \ + --analyzing-num-workers ${num_workers} \ + --analyzing-worker-id ${worker_id} \ + --analyzing-num-threads ${num_threads} \ + --vocab-file ${vocab_path} \ + --data-path ${data_path} \ + --data-impl mmap \ + --tokenizer-type BertWordPieceLowerCase \ + --micro-batch-size ${batch_size} \ + --global-batch-size ${batch_size} \ + --seq-length ${seq_len} \ + --max-position-embeddings ${seq_len} \ + --num-layers 1 \ + --hidden-size 1 \ + --num-attention-heads 1 \ + --split 949,50,1 \ + --distributed-backend gloo \ + --train-data-exact-num-epochs ${num_epochs} \ + --return-data-index \ + --save-interval 1 \ + --save ${save_path}" + +python ../analyze_data.py ${options} &> ${jobname}.log \ No newline at end of file diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/bert/ds_analyze_bert_data_reduce.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/bert/ds_analyze_bert_data_reduce.sh new file mode 100644 index 0000000000000000000000000000000000000000..f0d14df96a52bbb7391e12c3140ac5536fcacacd --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/bert/ds_analyze_bert_data_reduce.sh @@ -0,0 +1,66 @@ +#!/bin/bash + +# Set these 2 to the same as what you used during map job. We need these 2 +# configs to know how many map job result files do we have. +num_workers=1 +num_threads=40 +# Reduce job only has 1 worker but can accelerate by multithreading. +num_threads_reduce=40 + +# If different data epochs have slightly different data samples (e.g., due +# to randomness), then you need to specify large enough num_epochs that cover +# whole pretraining. If different data epochs are the same, set num_epochs to +# 1 to only index 1 epoch, and during pretraining DeepSpeed data efficiency +# library will automatically handle reshuffling when reaching another epoch. +num_epochs=5 + +save_path="/blob/users/conglli/data/analysis_pile_bert_${num_epochs}epoch/" + +metric='total_vocab_freq' +# metric='vocab_rarity' # this requires the result of total_vocab_freq +# metric='seqlen_vocab_rarity' # this requires the result of total_vocab_freq +# metric='seqlen' + +seq_len=512 +batch_size=10000 + +jobname="bert-pile-analyzing-${metric}-${num_epochs}epoch-reduce" +## Public the Pile dataset, see prepare_pile_data.py in the same directory +## about how to download and preprocess the data. +## Change data_home to your own training data path. +# data_home="/vc_data_blob/users/conglli/the_pile_bert" +data_home="/blob/data/the_pile_bert" +data_path="${data_home}/pile_bert_train_text_sentence" + +vocab_path="bert-large-uncased-vocab.txt" +if [ ! -f "$vocab_path" ]; then + wget https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt +fi + +# Make sure the "--split" is the same as what you will use for pre-training. +options=" \ + --analyzing-task reduce \ + --analyzing-data-type BERT \ + --analyzing-metric ${metric} \ + --analyzing-num-workers ${num_workers} \ + --analyzing-num-threads ${num_threads} \ + --analyzing-num-threads-reduce ${num_threads_reduce} \ + --vocab-file ${vocab_path} \ + --data-path ${data_path} \ + --data-impl mmap \ + --tokenizer-type BertWordPieceLowerCase \ + --micro-batch-size ${batch_size} \ + --global-batch-size ${batch_size} \ + --seq-length ${seq_len} \ + --max-position-embeddings ${seq_len} \ + --num-layers 1 \ + --hidden-size 1 \ + --num-attention-heads 1 \ + --split 949,50,1 \ + --distributed-backend gloo \ + --train-data-exact-num-epochs ${num_epochs} \ + --return-data-index \ + --save-interval 1 \ + --save ${save_path}" + +python ../analyze_data.py ${options} &> ${jobname}.log \ No newline at end of file diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/bert/finetune/ds_finetune_bert_mnli.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/bert/finetune/ds_finetune_bert_mnli.sh new file mode 100644 index 0000000000000000000000000000000000000000..e88f7beb0cf0349b81f149783c92b4b51ff0f157 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/bert/finetune/ds_finetune_bert_mnli.sh @@ -0,0 +1,150 @@ +seed=1234 +pretrained_checkpoint="/blob/users/conglli/project/bert_with_pile/checkpoint/bert-pile-0.336B-iters-2M-lr-1e-4-min-1e-5-wmup-10000-dcy-2M-sty-linear-gbs-1024-mbs-16-gpu-64-zero-0-mp-1-pp-1-nopp" + +############################################################################### +### Main configs +### The main configs are from Megatron-LM paper +### https://arxiv.org/abs/1909.08053. Choose based on your desired model size +### or build your own configs. +seq_len=512 + +## From Table 6 in https://arxiv.org/abs/1909.08053. +task="MNLI" +global_batch_size=128 +lr=1e-5 +epochs=10 + +train_data="/blob/data/GlueData/MNLI/train.tsv" +valid_data="/blob/data/GlueData/MNLI/dev_matched.tsv \ + /blob/data/GlueData/MNLI/dev_mismatched.tsv" + +## Adjust based on number of GPUs. +batch_size=16 + +## BERT 110M (same config as original BERT-Base model) +## This config is not included in Megatron-LM paper +# model_size=0.11 +# num_layers=12 +# hidden_size=768 +# num_attn_heads=12 + +## BERT 336M (same config as original BERT-Large model) +model_size=0.336 +num_layers=24 +hidden_size=1024 +num_attn_heads=16 + +## BERT 1.3B +# model_size=1.3 +# num_layers=24 +# hidden_size=2048 +# num_attn_heads=32 + +## BERT 3.9B +# model_size=3.9 +# num_layers=48 +# hidden_size=2560 +# num_attn_heads=40 +############################################################################### +### Parallelism configs +## Model parallelism, 1 is no MP +mp_size=1 + +## Pipeline parallelism. To disable PP, set pp_size to 1 and no_pp to true. +## Currently pipeline parallelism is not supported for BERT model: DeepSpeed's +## pipeline parallelism is only integrated with the GPT case, and currently +## DeepSpeed is not integrated with Megatron's own pipeline parallelism. +pp_size=1 +no_pp="true" + +## ZeRO stage +zero_stage=0 +############################################################################### +### Misc configs +log_interval=10 +eval_iters=50 +eval_interval=100 +save_interval=500000 + +## Activation checkpointing saves GPU memory, but reduces training speed +# activation_checkpoint="true" +activation_checkpoint="false" +############################################################################### +vocab_file="bert-large-uncased-vocab.txt" +if [ ! -f "$vocab_file" ]; then + wget https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt +fi + +jobname="${task}-bsz${global_batch_size}-lr${lr}-epochs${epochs}-seed${seed}" +checkpoint_path="${pretrained_checkpoint}-finetune/${jobname}" +mkdir -p ${checkpoint_path} + +template_json="ds_config_bert_TEMPLATE.json" +config_json="ds_config_bert_bsz${global_batch_size}_mbsz${batch_size}_log${log_interval}_zero${zero_stage}.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/" \ + > ${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/" \ + > ${config_json} +fi + +options=" \ + --finetune \ + --deepspeed \ + --deepspeed_config ${config_json} \ + --zero-stage ${zero_stage} \ + --task ${task} \ + --seed ${seed} \ + --train-data ${train_data} \ + --valid-data ${valid_data} \ + --tokenizer-type BertWordPieceLowerCase \ + --vocab-file ${vocab_file} \ + --epochs ${epochs} \ + --pretrained-checkpoint ${pretrained_checkpoint} \ + --tensor-model-parallel-size ${mp_size} \ + --pipeline-model-parallel-size ${pp_size} \ + --num-layers ${num_layers} \ + --hidden-size ${hidden_size} \ + --num-attention-heads ${num_attn_heads} \ + --global-batch-size ${global_batch_size} \ + --micro-batch-size ${batch_size} \ + --lr ${lr} \ + --lr-decay-style linear \ + --lr-warmup-fraction 0.065 \ + --seq-length ${seq_len} \ + --max-position-embeddings ${seq_len} \ + --save-interval ${save_interval} \ + --save ${checkpoint_path} \ + --log-interval ${log_interval} \ + --eval-interval ${eval_interval} \ + --eval-iters ${eval_iters} \ + --weight-decay 1.0e-1 \ + --fp16" + +if [ "${activation_checkpoint}" = "true" ]; then +options="${options} \ + --checkpoint-activations \ + --deepspeed-activation-checkpointing" +fi + +if [[ "${no_pp}" = "true" ]]; then +options="${options} \ + --no-pipeline-parallel" +fi + +# After the fine-tuning finishes, you can find the dev set accuracy numbers by +# "grep -e "overall:" -e "metrics for" ${checkpoint_path}/output.log" +deepspeed ../../../../tasks/main.py ${options} &> ${checkpoint_path}/output.log diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/bert/finetune/ds_finetune_bert_qqp.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/bert/finetune/ds_finetune_bert_qqp.sh new file mode 100644 index 0000000000000000000000000000000000000000..8083e1024d607e4bc37f6cdb560f762b5fabc490 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/bert/finetune/ds_finetune_bert_qqp.sh @@ -0,0 +1,158 @@ +seed=1234 +pretrained_checkpoint="/blob/users/conglli/project/bert_with_pile/checkpoint/bert-pile-0.336B-iters-2M-lr-1e-4-min-1e-5-wmup-10000-dcy-2M-sty-linear-gbs-1024-mbs-16-gpu-64-zero-0-mp-1-pp-1-nopp" + +############################################################################### +### Main configs +### The main configs are from Megatron-LM paper +### https://arxiv.org/abs/1909.08053. Choose based on your desired model size +### or build your own configs. +seq_len=512 + +## From Table 6 in https://arxiv.org/abs/1909.08053. +task="QQP" + +train_data="/blob/data/GlueData/QQP/train.tsv" +valid_data="/blob/data/GlueData/QQP/dev.tsv" + +## Adjust based on number of GPUs. +batch_size=16 + +## BERT 110M (same config as original BERT-Base model) +## This config is not included in Megatron-LM paper +# model_size=0.11 +# num_layers=12 +# hidden_size=768 +# num_attn_heads=12 +# global_batch_size=128 +# lr=5e-5 +# epochs=12 + +## BERT 336M (same config as original BERT-Large model) +model_size=0.336 +num_layers=24 +hidden_size=1024 +num_attn_heads=16 +global_batch_size=128 +lr=5e-5 +epochs=12 + +## BERT 1.3B +# model_size=1.3 +# num_layers=24 +# hidden_size=2048 +# num_attn_heads=32 +# global_batch_size=128 +# lr=3e-5 +# epochs=12 + +## BERT 3.9B +# model_size=3.9 +# num_layers=48 +# hidden_size=2560 +# num_attn_heads=40 +# global_batch_size=256 +# lr=4e-5 +# epochs=12 +############################################################################### +### Parallelism configs +## Model parallelism, 1 is no MP +mp_size=1 + +## Pipeline parallelism. To disable PP, set pp_size to 1 and no_pp to true. +## Currently pipeline parallelism is not supported for BERT model: DeepSpeed's +## pipeline parallelism is only integrated with the GPT case, and currently +## DeepSpeed is not integrated with Megatron's own pipeline parallelism. +pp_size=1 +no_pp="true" + +## ZeRO stage +zero_stage=0 +############################################################################### +### Misc configs +log_interval=10 +eval_iters=50 +eval_interval=100 +save_interval=500000 + +## Activation checkpointing saves GPU memory, but reduces training speed +# activation_checkpoint="true" +activation_checkpoint="false" +############################################################################### +vocab_file="bert-large-uncased-vocab.txt" +if [ ! -f "$vocab_file" ]; then + wget https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt +fi + +jobname="${task}-bsz${global_batch_size}-lr${lr}-epochs${epochs}-seed${seed}" +checkpoint_path="${pretrained_checkpoint}-finetune/${jobname}" +mkdir -p ${checkpoint_path} + +template_json="ds_config_bert_TEMPLATE.json" +config_json="ds_config_bert_bsz${global_batch_size}_mbsz${batch_size}_log${log_interval}_zero${zero_stage}.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/" \ + > ${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/" \ + > ${config_json} +fi + +options=" \ + --finetune \ + --deepspeed \ + --deepspeed_config ${config_json} \ + --zero-stage ${zero_stage} \ + --task ${task} \ + --seed ${seed} \ + --train-data ${train_data} \ + --valid-data ${valid_data} \ + --tokenizer-type BertWordPieceLowerCase \ + --vocab-file ${vocab_file} \ + --epochs ${epochs} \ + --pretrained-checkpoint ${pretrained_checkpoint} \ + --tensor-model-parallel-size ${mp_size} \ + --pipeline-model-parallel-size ${pp_size} \ + --num-layers ${num_layers} \ + --hidden-size ${hidden_size} \ + --num-attention-heads ${num_attn_heads} \ + --global-batch-size ${global_batch_size} \ + --micro-batch-size ${batch_size} \ + --lr ${lr} \ + --lr-decay-style linear \ + --lr-warmup-fraction 0.065 \ + --seq-length ${seq_len} \ + --max-position-embeddings ${seq_len} \ + --save-interval ${save_interval} \ + --save ${checkpoint_path} \ + --log-interval ${log_interval} \ + --eval-interval ${eval_interval} \ + --eval-iters ${eval_iters} \ + --weight-decay 1.0e-1 \ + --fp16" + +if [ "${activation_checkpoint}" = "true" ]; then +options="${options} \ + --checkpoint-activations \ + --deepspeed-activation-checkpointing" +fi + +if [[ "${no_pp}" = "true" ]]; then +options="${options} \ + --no-pipeline-parallel" +fi + +# After the fine-tuning finishes, you can find the dev set accuracy numbers by +# "grep -e "overall:" -e "metrics for" ${checkpoint_path}/output.log" +deepspeed ../../../../tasks/main.py ${options} &> ${checkpoint_path}/output.log diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/bert/pretrain/ds_config_bert_1clmetric_TEMPLATE.json b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/bert/pretrain/ds_config_bert_1clmetric_TEMPLATE.json new file mode 100644 index 0000000000000000000000000000000000000000..cca845096a0af2c65d6cdf25a76b30b5239198df --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/bert/pretrain/ds_config_bert_1clmetric_TEMPLATE.json @@ -0,0 +1,73 @@ +{ + "train_batch_size": GBSIZE, + "train_micro_batch_size_per_gpu": MBSIZE, + "steps_per_print": LOG_INTERVAL, + + "zero_optimization": { + "stage": ZERO_STAGE + }, + + "gradient_clipping": 1.0, + "prescale_gradients": PRESCALE_GRAD, + + "fp16": { + "enabled": true, + "loss_scale": 0, + "loss_scale_window": 500, + "hysteresis": 2, + "min_loss_scale": 1, + "initial_scale_power": 11 + }, + + "wall_clock_breakdown" : false, + "dataloader_drop_last": true, + "data_efficiency": { + "enabled": true, + "seed": DATA_EFFICIENCY_SEED, + "data_routing": { + "enabled": LTD_ENABLED, + "random_ltd":{ + "enabled": LTD_ENABLED, + "total_layer_num": 24, + "random_ltd_layer_num": 22, + "random_ltd_layer_id": [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22], + "model_mask_name": "attention_mask", + "model_type": "encoder", + "hidden_state_order": "seq_batch_dim", + "random_ltd_schedule": { + "min_value": LTD_MIN, + "max_value": LTD_MAX, + "schedule_type":"fixed_linear", + "schedule_config": { + "require_steps": LTD_STEP, + "seq_per_step": 16 + } + } + } + }, + "data_sampling": { + "enabled": CL_ENABLED, + "num_workers": DATA_SAMPLING_NUM_WORKERS, + "curriculum_learning": { + "enabled": CL_ENABLED, + "data_cluster_path": "CL_CLUSTER_PATH", + "curriculum_metrics": { + "CL_1st_METRIC_NAME": { + "index_to_sample_path": "CL_1st_SAMPLE_PATH", + "index_to_metric_path": "CL_1st_METRIC_PATH", + "difficulty_type": "CL_1st_DIFF_TYPE", + "clustering_type": "CL_1st_CLUSTER_TYPE", + "min_difficulty": CL_1st_MIN, + "max_difficulty": CL_1st_MAX, + "schedule_type": "fixed_root", + "schedule_config": { + "total_curriculum_step": CL_1st_TOTAL_STEP, + "difficulty_step": CL_1st_DIFF_STEP, + "root_degree": CL_1st_ROOT + } + } + } + } + } + } +} diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/bert/pretrain/ds_config_bert_2clmetrics_TEMPLATE.json b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/bert/pretrain/ds_config_bert_2clmetrics_TEMPLATE.json new file mode 100644 index 0000000000000000000000000000000000000000..9461d6d5d73f6196970119444791e2e17aa175c6 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/bert/pretrain/ds_config_bert_2clmetrics_TEMPLATE.json @@ -0,0 +1,87 @@ +{ + "train_batch_size": GBSIZE, + "train_micro_batch_size_per_gpu": MBSIZE, + "steps_per_print": LOG_INTERVAL, + + "zero_optimization": { + "stage": ZERO_STAGE + }, + + "gradient_clipping": 1.0, + "prescale_gradients": PRESCALE_GRAD, + + "fp16": { + "enabled": true, + "loss_scale": 0, + "loss_scale_window": 500, + "hysteresis": 2, + "min_loss_scale": 1, + "initial_scale_power": 11 + }, + + "wall_clock_breakdown" : false, + "dataloader_drop_last": true, + "data_efficiency": { + "enabled": true, + "seed": DATA_EFFICIENCY_SEED, + "data_routing": { + "enabled": LTD_ENABLED, + "random_ltd":{ + "enabled": LTD_ENABLED, + "total_layer_num": 24, + "random_ltd_layer_num": 22, + "random_ltd_layer_id": [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22], + "model_mask_name": "attention_mask", + "model_type": "encoder", + "hidden_state_order": "seq_batch_dim", + "random_ltd_schedule": { + "min_value": LTD_MIN, + "max_value": LTD_MAX, + "schedule_type":"fixed_linear", + "schedule_config": { + "require_steps": LTD_STEP, + "seq_per_step": 16 + } + } + } + }, + "data_sampling": { + "enabled": CL_ENABLED, + "num_workers": DATA_SAMPLING_NUM_WORKERS, + "curriculum_learning": { + "enabled": CL_ENABLED, + "data_cluster_path": "CL_CLUSTER_PATH", + "curriculum_metrics": { + "CL_1st_METRIC_NAME": { + "index_to_sample_path": "CL_1st_SAMPLE_PATH", + "index_to_metric_path": "CL_1st_METRIC_PATH", + "difficulty_type": "CL_1st_DIFF_TYPE", + "clustering_type": "CL_1st_CLUSTER_TYPE", + "min_difficulty": CL_1st_MIN, + "max_difficulty": CL_1st_MAX, + "schedule_type": "fixed_root", + "schedule_config": { + "total_curriculum_step": CL_1st_TOTAL_STEP, + "difficulty_step": CL_1st_DIFF_STEP, + "root_degree": CL_1st_ROOT + } + }, + "CL_2nd_METRIC_NAME": { + "index_to_sample_path": "CL_2nd_SAMPLE_PATH", + "index_to_metric_path": "CL_2nd_METRIC_PATH", + "difficulty_type": "CL_2nd_DIFF_TYPE", + "clustering_type": "CL_2nd_CLUSTER_TYPE", + "min_difficulty": CL_2nd_MIN, + "max_difficulty": CL_2nd_MAX, + "schedule_type": "fixed_root", + "schedule_config": { + "total_curriculum_step": CL_2nd_TOTAL_STEP, + "difficulty_step": CL_2nd_DIFF_STEP, + "root_degree": CL_2nd_ROOT + } + } + } + } + } + } +} diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/bert/pretrain/ds_pretrain_bert_336M_run.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/bert/pretrain/ds_pretrain_bert_336M_run.sh new file mode 100644 index 0000000000000000000000000000000000000000..c771a0e27726b4bfc23e3999f8b590a90c1f0699 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/data_efficiency/bert/pretrain/ds_pretrain_bert_336M_run.sh @@ -0,0 +1,363 @@ +############################################################################### +### Each block below is one pretraining setup. Uncomment one block to try. +############################################################################### +### Baseline cases, mostly based on Megatron-LM's BERT-Large hyperparameters, +### but with some changes (different LR schedule). +## Baseline 1049B tokens (100%): +# lr=1e-4 +# train_iters_in_million=2 +# bash ds_pretrain_bert_336M_base_script.sh ${lr} ${train_iters_in_million} +############################################################################### +## Baseline 703B tokens (67%): +# lr=1.5e-4 +# train_iters_in_million=134e-2 +# bash ds_pretrain_bert_336M_base_script.sh ${lr} ${train_iters_in_million} +############################################################################### +## Baseline 524B tokens (50%): +# lr=2e-4 +# train_iters_in_million=1 +# bash ds_pretrain_bert_336M_base_script.sh ${lr} ${train_iters_in_million} +############################################################################### +### Curriculum learning (CL) + Random layerwise token dropping (random-LTD). +### DeepSpeed Data Efficiency's composed solution. +### BERT pretraining. +## CL+random-LTD 1049B tokens (100%): +# lr=1e-4 +# train_iters_in_million=2 +# ltd_enabled="true" +# ltd_start=128 +# ltd_step_in_million=2 +# dropout=1e-1 +# cl_enabled="true" +# cl_num_metric=2 +# cl_1st_metric="voc" +# cl_1st_index_to_sample_path="/vc_data/users/conglli/code/data_efficiency/data/analysis_pile_bert_5epoch/vocab_rarity/vocab_rarity_index_to_sample_percentile_merged" +# cl_1st_index_to_metric_path="/vc_data/users/conglli/code/data_efficiency/data/analysis_pile_bert_5epoch/vocab_rarity/vocab_rarity_index_to_metric" +# cl_1st_difficulty_type="percentile" +# cl_1st_clustering_type="schedule_based" +# cl_1st_min=5 +# cl_1st_max=100 +# cl_1st_total_step_in_million=96e-2 +# cl_1st_difficulty_step=1 +# cl_1st_root=2 +# cl_2nd_metric="seqlen_truncate" +# cl_2nd_index_to_sample_path="dummy" +# cl_2nd_index_to_metric_path="dummy" +# cl_2nd_difficulty_type="value" +# cl_2nd_clustering_type="single_cluster" +# cl_2nd_min=128 +# cl_2nd_max=512 +# cl_2nd_total_step_in_million=96e-2 +# cl_2nd_difficulty_step=8 +# cl_2nd_root=1 +# bash ds_pretrain_bert_336M_base_script.sh ${lr} ${train_iters_in_million} \ +# ${ltd_enabled} ${ltd_start} ${ltd_step_in_million} ${dropout} \ +# ${cl_enabled} ${cl_num_metric} ${cl_1st_metric} \ +# ${cl_1st_index_to_sample_path} ${cl_1st_index_to_metric_path} \ +# ${cl_1st_difficulty_type} ${cl_1st_clustering_type} ${cl_1st_min} \ +# ${cl_1st_max} ${cl_1st_total_step_in_million} ${cl_1st_difficulty_step} \ +# ${cl_1st_root} ${cl_2nd_metric} ${cl_2nd_index_to_sample_path} \ +# ${cl_2nd_index_to_metric_path} ${cl_2nd_difficulty_type} \ +# ${cl_2nd_clustering_type} ${cl_2nd_min} ${cl_2nd_max} \ +# ${cl_2nd_total_step_in_million} ${cl_2nd_difficulty_step} ${cl_2nd_root} +############################################################################### +## CL+random-LTD 524B tokens (50%): +# lr=2e-4 +# train_iters_in_million=1 +# ltd_enabled="true" +# ltd_start=128 +# ltd_step_in_million=1 +# dropout=1e-1 +# cl_enabled="true" +# cl_num_metric=2 +# cl_1st_metric="voc" +# cl_1st_index_to_sample_path="/vc_data/users/conglli/code/data_efficiency/data/analysis_pile_bert_5epoch/vocab_rarity/vocab_rarity_index_to_sample_percentile_merged" +# cl_1st_index_to_metric_path="/vc_data/users/conglli/code/data_efficiency/data/analysis_pile_bert_5epoch/vocab_rarity/vocab_rarity_index_to_metric" +# cl_1st_difficulty_type="percentile" +# cl_1st_clustering_type="schedule_based" +# cl_1st_min=5 +# cl_1st_max=100 +# cl_1st_total_step_in_million=48e-2 +# cl_1st_difficulty_step=1 +# cl_1st_root=2 +# cl_2nd_metric="seqlen_truncate" +# cl_2nd_index_to_sample_path="dummy" +# cl_2nd_index_to_metric_path="dummy" +# cl_2nd_difficulty_type="value" +# cl_2nd_clustering_type="single_cluster" +# cl_2nd_min=128 +# cl_2nd_max=512 +# cl_2nd_total_step_in_million=48e-2 +# cl_2nd_difficulty_step=8 +# cl_2nd_root=1 +# bash ds_pretrain_bert_336M_base_script.sh ${lr} ${train_iters_in_million} \ +# ${ltd_enabled} ${ltd_start} ${ltd_step_in_million} ${dropout} \ +# ${cl_enabled} ${cl_num_metric} ${cl_1st_metric} \ +# ${cl_1st_index_to_sample_path} ${cl_1st_index_to_metric_path} \ +# ${cl_1st_difficulty_type} ${cl_1st_clustering_type} ${cl_1st_min} \ +# ${cl_1st_max} ${cl_1st_total_step_in_million} ${cl_1st_difficulty_step} \ +# ${cl_1st_root} ${cl_2nd_metric} ${cl_2nd_index_to_sample_path} \ +# ${cl_2nd_index_to_metric_path} ${cl_2nd_difficulty_type} \ +# ${cl_2nd_clustering_type} ${cl_2nd_min} ${cl_2nd_max} \ +# ${cl_2nd_total_step_in_million} ${cl_2nd_difficulty_step} ${cl_2nd_root} +############################################################################### +### Random layerwise token dropping (random-LTD). +## random-LTD 1049B tokens (100%): +# lr=1e-4 +# train_iters_in_million=2 +# ltd_enabled="true" +# ltd_start=128 +# ltd_step_in_million=2 +# dropout=1e-1 +# bash ds_pretrain_bert_336M_base_script.sh ${lr} ${train_iters_in_million} \ +# ${ltd_enabled} ${ltd_start} ${ltd_step_in_million} ${dropout} +############################################################################### +## random-LTD 703B tokens (67%): +# lr=1.5e-4 +# train_iters_in_million=134e-2 +# ltd_enabled="true" +# ltd_start=128 +# ltd_step_in_million=134e-2 +# dropout=1e-1 +# bash ds_pretrain_bert_336M_base_script.sh ${lr} ${train_iters_in_million} \ +# ${ltd_enabled} ${ltd_start} ${ltd_step_in_million} ${dropout} +############################################################################### +## random-LTD 524B tokens (50%): +# lr=2e-4 +# train_iters_in_million=1 +# ltd_enabled="true" +# ltd_start=128 +# ltd_step_in_million=1 +# dropout=1e-1 +# bash ds_pretrain_bert_336M_base_script.sh ${lr} ${train_iters_in_million} \ +# ${ltd_enabled} ${ltd_start} ${ltd_step_in_million} ${dropout} +############################################################################### +### Curriculum learning (CL). +## CL vocab rarity + seqlen truncation 524B tokens (50%): +# lr=2e-4 +# train_iters_in_million=1 +# ltd_enabled="false" +# ltd_start=512 +# ltd_step_in_million=1 +# dropout=1e-1 +# cl_enabled="true" +# cl_num_metric=2 +# cl_1st_metric="voc" +# cl_1st_index_to_sample_path="/vc_data/users/conglli/code/data_efficiency/data/analysis_pile_bert_5epoch/vocab_rarity/vocab_rarity_index_to_sample_percentile_merged" +# cl_1st_index_to_metric_path="/vc_data/users/conglli/code/data_efficiency/data/analysis_pile_bert_5epoch/vocab_rarity/vocab_rarity_index_to_metric" +# cl_1st_difficulty_type="percentile" +# cl_1st_clustering_type="schedule_based" +# cl_1st_min=5 +# cl_1st_max=100 +# cl_1st_total_step_in_million=48e-2 +# cl_1st_difficulty_step=1 +# cl_1st_root=2 +# cl_2nd_metric="seqlen_truncate" +# cl_2nd_index_to_sample_path="dummy" +# cl_2nd_index_to_metric_path="dummy" +# cl_2nd_difficulty_type="value" +# cl_2nd_clustering_type="single_cluster" +# cl_2nd_min=128 +# cl_2nd_max=512 +# cl_2nd_total_step_in_million=48e-2 +# cl_2nd_difficulty_step=8 +# cl_2nd_root=1 +# bash ds_pretrain_bert_336M_base_script.sh ${lr} ${train_iters_in_million} \ +# ${ltd_enabled} ${ltd_start} ${ltd_step_in_million} ${dropout} \ +# ${cl_enabled} ${cl_num_metric} ${cl_1st_metric} \ +# ${cl_1st_index_to_sample_path} ${cl_1st_index_to_metric_path} \ +# ${cl_1st_difficulty_type} ${cl_1st_clustering_type} ${cl_1st_min} \ +# ${cl_1st_max} ${cl_1st_total_step_in_million} ${cl_1st_difficulty_step} \ +# ${cl_1st_root} ${cl_2nd_metric} ${cl_2nd_index_to_sample_path} \ +# ${cl_2nd_index_to_metric_path} ${cl_2nd_difficulty_type} \ +# ${cl_2nd_clustering_type} ${cl_2nd_min} ${cl_2nd_max} \ +# ${cl_2nd_total_step_in_million} ${cl_2nd_difficulty_step} ${cl_2nd_root} +############################################################################### +## CL vocab rarity + seqlen truncation 703B tokens (67%): +# lr=1.5e-4 +# train_iters_in_million=134e-2 +# ltd_enabled="false" +# ltd_start=512 +# ltd_step_in_million=1 +# dropout=1e-1 +# cl_enabled="true" +# cl_num_metric=2 +# cl_1st_metric="voc" +# cl_1st_index_to_sample_path="/vc_data/users/conglli/code/data_efficiency/data/analysis_pile_bert_5epoch/vocab_rarity/vocab_rarity_index_to_sample_percentile_merged" +# cl_1st_index_to_metric_path="/vc_data/users/conglli/code/data_efficiency/data/analysis_pile_bert_5epoch/vocab_rarity/vocab_rarity_index_to_metric" +# cl_1st_difficulty_type="percentile" +# cl_1st_clustering_type="schedule_based" +# cl_1st_min=5 +# cl_1st_max=100 +# cl_1st_total_step_in_million=64e-2 +# cl_1st_difficulty_step=1 +# cl_1st_root=2 +# cl_2nd_metric="seqlen_truncate" +# cl_2nd_index_to_sample_path="dummy" +# cl_2nd_index_to_metric_path="dummy" +# cl_2nd_difficulty_type="value" +# cl_2nd_clustering_type="single_cluster" +# cl_2nd_min=128 +# cl_2nd_max=512 +# cl_2nd_total_step_in_million=64e-2 +# cl_2nd_difficulty_step=8 +# cl_2nd_root=1 +# bash ds_pretrain_bert_336M_base_script.sh ${lr} ${train_iters_in_million} \ +# ${ltd_enabled} ${ltd_start} ${ltd_step_in_million} ${dropout} \ +# ${cl_enabled} ${cl_num_metric} ${cl_1st_metric} \ +# ${cl_1st_index_to_sample_path} ${cl_1st_index_to_metric_path} \ +# ${cl_1st_difficulty_type} ${cl_1st_clustering_type} ${cl_1st_min} \ +# ${cl_1st_max} ${cl_1st_total_step_in_million} ${cl_1st_difficulty_step} \ +# ${cl_1st_root} ${cl_2nd_metric} ${cl_2nd_index_to_sample_path} \ +# ${cl_2nd_index_to_metric_path} ${cl_2nd_difficulty_type} \ +# ${cl_2nd_clustering_type} ${cl_2nd_min} ${cl_2nd_max} \ +# ${cl_2nd_total_step_in_million} ${cl_2nd_difficulty_step} ${cl_2nd_root} +############################################################################### +## CL vocab rarity + seqlen truncation 1049B tokens (100%): +# lr=1e-4 +# train_iters_in_million=2 +# ltd_enabled="false" +# ltd_start=512 +# ltd_step_in_million=1 +# dropout=1e-1 +# cl_enabled="true" +# cl_num_metric=2 +# cl_1st_metric="voc" +# cl_1st_index_to_sample_path="/blob/users/conglli/data/analysis_pile_bert_5epoch/vocab_rarity/vocab_rarity_index_to_sample" +# cl_1st_index_to_metric_path="/blob/users/conglli/data/analysis_pile_bert_5epoch/vocab_rarity/vocab_rarity_index_to_metric" +# cl_1st_difficulty_type="percentile" +# cl_1st_clustering_type="schedule_based" +# cl_1st_min=5 +# cl_1st_max=100 +# cl_1st_total_step_in_million=96e-2 +# cl_1st_difficulty_step=1 +# cl_1st_root=2 +# cl_2nd_metric="seqlen_truncate" +# cl_2nd_index_to_sample_path="dummy" +# cl_2nd_index_to_metric_path="dummy" +# cl_2nd_difficulty_type="value" +# cl_2nd_clustering_type="single_cluster" +# cl_2nd_min=128 +# cl_2nd_max=512 +# cl_2nd_total_step_in_million=96e-2 +# cl_2nd_difficulty_step=8 +# cl_2nd_root=1 +# bash ds_pretrain_bert_336M_base_script.sh ${lr} ${train_iters_in_million} \ +# ${ltd_enabled} ${ltd_start} ${ltd_step_in_million} ${dropout} \ +# ${cl_enabled} ${cl_num_metric} ${cl_1st_metric} \ +# ${cl_1st_index_to_sample_path} ${cl_1st_index_to_metric_path} \ +# ${cl_1st_difficulty_type} ${cl_1st_clustering_type} ${cl_1st_min} \ +# ${cl_1st_max} ${cl_1st_total_step_in_million} ${cl_1st_difficulty_step} \ +# ${cl_1st_root} ${cl_2nd_metric} ${cl_2nd_index_to_sample_path} \ +# ${cl_2nd_index_to_metric_path} ${cl_2nd_difficulty_type} \ +# ${cl_2nd_clustering_type} ${cl_2nd_min} ${cl_2nd_max} \ +# ${cl_2nd_total_step_in_million} ${cl_2nd_difficulty_step} ${cl_2nd_root} +############################################################################### +## CL vocab rarity + seqlen reorder 1049B tokens (100%): +# lr=1e-4 +# train_iters_in_million=2 +# ltd_enabled="false" +# ltd_start=512 +# ltd_step_in_million=1 +# dropout=1e-1 +# cl_enabled="true" +# cl_num_metric=1 +# cl_1st_metric="seqlenvocabrarity" +# cl_1st_index_to_sample_path="/blob/users/conglli/data/analysis_pile_bert_5epoch/seqlen_vocab_rarity/seqlen_vocab_rarity_index_to_sample_percentile_merged" +# cl_1st_index_to_metric_path="/blob/users/conglli/data/analysis_pile_bert_5epoch/seqlen_vocab_rarity/seqlen_vocab_rarity_index_to_metric" +# cl_1st_difficulty_type="percentile" +# cl_1st_clustering_type="schedule_based" +# cl_1st_min=5 +# cl_1st_max=100 +# cl_1st_total_step_in_million=96e-2 +# cl_1st_difficulty_step=1 +# cl_1st_root=2 +# bash ds_pretrain_bert_336M_base_script.sh ${lr} ${train_iters_in_million} \ +# ${ltd_enabled} ${ltd_start} ${ltd_step_in_million} ${dropout} \ +# ${cl_enabled} ${cl_num_metric} ${cl_1st_metric} \ +# ${cl_1st_index_to_sample_path} ${cl_1st_index_to_metric_path} \ +# ${cl_1st_difficulty_type} ${cl_1st_clustering_type} ${cl_1st_min} \ +# ${cl_1st_max} ${cl_1st_total_step_in_million} ${cl_1st_difficulty_step} \ +# ${cl_1st_root} +############################################################################### +## CL vocab rarity 1049B tokens (100%): +# lr=1e-4 +# train_iters_in_million=2 +# ltd_enabled="false" +# ltd_start=512 +# ltd_step_in_million=1 +# dropout=1e-1 +# cl_enabled="true" +# cl_num_metric=1 +# cl_1st_metric="voc" +# cl_1st_index_to_sample_path="/blob/users/conglli/data/analysis_pile_bert_5epoch/vocab_rarity/vocab_rarity_index_to_sample" +# cl_1st_index_to_metric_path="/blob/users/conglli/data/analysis_pile_bert_5epoch/vocab_rarity/vocab_rarity_index_to_metric" +# cl_1st_difficulty_type="percentile" +# cl_1st_clustering_type="schedule_based" +# cl_1st_min=5 +# cl_1st_max=100 +# cl_1st_total_step_in_million=96e-2 +# cl_1st_difficulty_step=1 +# cl_1st_root=2 +# bash ds_pretrain_bert_336M_base_script.sh ${lr} ${train_iters_in_million} \ +# ${ltd_enabled} ${ltd_start} ${ltd_step_in_million} ${dropout} \ +# ${cl_enabled} ${cl_num_metric} ${cl_1st_metric} \ +# ${cl_1st_index_to_sample_path} ${cl_1st_index_to_metric_path} \ +# ${cl_1st_difficulty_type} ${cl_1st_clustering_type} ${cl_1st_min} \ +# ${cl_1st_max} ${cl_1st_total_step_in_million} ${cl_1st_difficulty_step} \ +# ${cl_1st_root} +############################################################################### +## CL seqlen truncation 1049B tokens (100%): +# lr=1e-4 +# train_iters_in_million=2 +# ltd_enabled="false" +# ltd_start=512 +# ltd_step_in_million=1 +# dropout=1e-1 +# cl_enabled="true" +# cl_num_metric=1 +# cl_1st_metric="seqlen_truncate" +# cl_1st_index_to_sample_path="dummy" +# cl_1st_index_to_metric_path="dummy" +# cl_1st_difficulty_type="value" +# cl_1st_clustering_type="single_cluster" +# cl_1st_min=128 +# cl_1st_max=512 +# cl_1st_total_step_in_million=96e-2 +# cl_1st_difficulty_step=8 +# cl_1st_root=1 +# bash ds_pretrain_bert_336M_base_script.sh ${lr} ${train_iters_in_million} \ +# ${ltd_enabled} ${ltd_start} ${ltd_step_in_million} ${dropout} \ +# ${cl_enabled} ${cl_num_metric} ${cl_1st_metric} \ +# ${cl_1st_index_to_sample_path} ${cl_1st_index_to_metric_path} \ +# ${cl_1st_difficulty_type} ${cl_1st_clustering_type} ${cl_1st_min} \ +# ${cl_1st_max} ${cl_1st_total_step_in_million} ${cl_1st_difficulty_step} \ +# ${cl_1st_root} +############################################################################### +## CL seqlen reorder 1049B tokens (100%): +# lr=1e-4 +# train_iters_in_million=2 +# ltd_enabled="false" +# ltd_start=512 +# ltd_step_in_million=1 +# dropout=1e-1 +# cl_enabled="true" +# cl_num_metric=1 +# cl_1st_metric="seqlen" +# cl_1st_index_to_sample_path="/blob/users/conglli/data/analysis_pile_bert_5epoch/seqlen/seqlen_index_to_sample_percentile_merged" +# cl_1st_index_to_metric_path="/blob/users/conglli/data/analysis_pile_bert_5epoch/seqlen/seqlen_index_to_metric" +# cl_1st_difficulty_type="percentile" +# cl_1st_clustering_type="single_cluster" +# cl_1st_min=5 +# cl_1st_max=100 +# cl_1st_total_step_in_million=96e-2 +# cl_1st_difficulty_step=8 +# cl_1st_root=2 +# bash ds_pretrain_bert_336M_base_script.sh ${lr} ${train_iters_in_million} \ +# ${ltd_enabled} ${ltd_start} ${ltd_step_in_million} ${dropout} \ +# ${cl_enabled} ${cl_num_metric} ${cl_1st_metric} \ +# ${cl_1st_index_to_sample_path} ${cl_1st_index_to_metric_path} \ +# ${cl_1st_difficulty_type} ${cl_1st_clustering_type} ${cl_1st_min} \ +# ${cl_1st_max} ${cl_1st_total_step_in_million} ${cl_1st_difficulty_step} \ +# ${cl_1st_root} +############################################################################### \ No newline at end of file diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/generate_text.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/generate_text.sh new file mode 100644 index 0000000000000000000000000000000000000000..e29d521e1ccb0c98198c9040781e4fc38841b072 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/generate_text.sh @@ -0,0 +1,51 @@ +#!/bin/bash +export TORCH_CUDA_ARCH_LIST=8.6+PTX +CHECKPOINT_PATH=dataset/checkpoints/gpt2_345m +VOCAB_FILE=dataset/gpt2-vocab.json +MERGE_FILE=dataset/gpt2-merges.txt +b=8 +mp=1 +experts=1 +nodes=1 +gpus=1 + + +use_tutel="" +#use_tutel="--use-tutel" + + +ds_inference="" +#ds_inference="--ds-inference" + +export CUDA_DEVICE_MAX_CONNECTIONS=1 + +launch_cmd="deepspeed --num_nodes $nodes --num_gpus $gpus" +L=24 +H=1024 +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 1024 \ + --out-seq-length 1024 \ + --temperature 1.0 \ + --vocab-file $VOCAB_FILE \ + --merge-file $MERGE_FILE \ + --genfile unconditional_samples.json \ + --top_p 0.9 \ + --log-interval 1 \ + --num-samples 0 \ + --load $CHECKPOINT_PATH \ + $use_tutel $ds_inference" + +echo $launch_cmd $program_cmd +$launch_cmd $program_cmd diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/pretrain_llama2_distributed.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/pretrain_llama2_distributed.sh new file mode 100644 index 0000000000000000000000000000000000000000..f275ea636a5e3756995484fe71b5070ef65089dd --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/pretrain_llama2_distributed.sh @@ -0,0 +1,135 @@ +#!/bin/bash +# This example script is contributed by external user https://github.com/nrailgun +set -ex + +###################################### +# Change the below configurations here +BASE_PATH=./tmp +DS_CONFIG=${BASE_PATH}/deepspeed.json +DATASET_1="./tmp/data/bookcorpus_train_1m_text_sentence" +DATASET="1 ${DATASET_1}" +CHECKPOINT_PATH=./tmp +TOKENIZER_PATH=./tmp/tokenizer.model # offical llama tokenizer.model + +TP=2 +PP=2 +ZERO_STAGE=0 + +GPUS_PER_NODE=8 +MASTER_ADDR=localhost +MASTER_PORT=6000 +NNODES=1 +NODE_RANK=0 + +HIDDEN_SIZE=2048 # e.g. llama-13b: 5120 +FFN_HIDDEN_SIZE=5504 # e.g. llama-13b: 13824 +NUM_LAYERS=24 # e.g. llama-13b: 40 +NUM_HEADS=16 # e.g. llama-13b: 40 +SEQ_LENGTH=2048 +NUM_KV_HEADS=4 # llama2 70B uses GQA + +MICRO_BATCH_SIZE=4 +GLOBAL_BATCH_SIZE=32 # e.g. llama: 4M tokens +TRAIN_STEPS=250000 # e.g. llama: 1T tokens / 4M tokens_per_batch = 250000 steps +LR=3e-4 +MIN_LR=3e-5 +LR_WARMUP_STEPS=2000 +WEIGHT_DECAY=0.1 +GRAD_CLIP=1 + +## Activation checkpointing saves GPU memory, but reduces training speed +# activation_checkpoint="true" +activation_checkpoint="false" + +# Below configuration required for llama model as per llama paper +# --no-query-key-layer-scaling \ +# --attention-dropout 0 \ +# --hidden-dropout 0 \ +# --use-rotary-position-embeddings \ +# --untie-embeddings-and-output-weights \ +# --swiglu \ +# --normalization rmsnorm \ +# --disable-bias-linear \ +###################################### + + + +cat < $DS_CONFIG +{ + "train_batch_size" : $GLOBAL_BATCH_SIZE, + "train_micro_batch_size_per_gpu": $MICRO_BATCH_SIZE, + "steps_per_print": 1, + "zero_optimization": { + "stage": $ZERO_STAGE + }, + "bf16": { + "enabled": true + } +} +EOT + +ds_args="" +ds_args=" --deepspeed ${ds_args}" +ds_args=" --deepspeed_config=$DS_CONFIG ${ds_args}" +ds_args=" --zero-stage=$ZERO_STAGE ${ds_args}" + +if [ "${activation_checkpoint}" = "true" ]; then + ds_args="--deepspeed-activation-checkpointing ${ds_args}" + + ## old argument for recomputing the transformer layer + # ds_args="--checkpoint-activations ${ds_args}" + + ## new argument for recomputing the transformer layer + ds_args="--recompute-granularity full --recompute-method uniform ${ds_args}" + ## new argument for recomputing only the attention layer + # ds_args="--recompute-granularity selective ${ds_args}" +fi + + +DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT" + +torchrun $DISTRIBUTED_ARGS \ + pretrain_gpt.py \ + --tensor-model-parallel-size $TP \ + --pipeline-model-parallel-size $PP \ + --num-layers $NUM_LAYERS \ + --hidden-size $HIDDEN_SIZE \ + --ffn-hidden-size $FFN_HIDDEN_SIZE \ + --num-attention-heads $NUM_HEADS \ + --micro-batch-size $MICRO_BATCH_SIZE \ + --global-batch-size $GLOBAL_BATCH_SIZE \ + --seq-length $SEQ_LENGTH \ + --max-position-embeddings $SEQ_LENGTH \ + --train-iters $TRAIN_STEPS \ + --save $CHECKPOINT_PATH \ + --load $CHECKPOINT_PATH \ + --data-path $DATASET \ + --data-impl mmap \ + --tokenizer-type GPTSentencePieceTokenizer \ + --tokenizer-model $TOKENIZER_PATH \ + --split 949,50,1 \ + --distributed-backend nccl \ + --lr $LR \ + --lr-decay-style cosine \ + --min-lr $MIN_LR \ + --weight-decay $WEIGHT_DECAY \ + --clip-grad $GRAD_CLIP \ + --lr-warmup-iters $LR_WARMUP_STEPS \ + --optimizer adam \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --log-interval 1 \ + --save-interval 10000 \ + --eval-interval 1000 \ + --eval-iters 10 \ + --bf16 \ + --no-query-key-layer-scaling \ + --attention-dropout 0 \ + --hidden-dropout 0 \ + --use-rotary-position-embeddings \ + --untie-embeddings-and-output-weights \ + --swiglu \ + --normalization rmsnorm \ + --disable-bias-linear \ + --num-key-value-heads $NUM_KV_HEADS \ + $ds_args diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/pretrain_llama_distributed.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/pretrain_llama_distributed.sh new file mode 100644 index 0000000000000000000000000000000000000000..b7bf890236fe4d4b04912d0fba7b26814de8159d --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/pretrain_llama_distributed.sh @@ -0,0 +1,132 @@ +#!/bin/bash +# This example script is contributed by external user https://github.com/LydiaXiaohongLi +set -ex + +###################################### +# Change the below configurations here +BASE_PATH=./tmp +DS_CONFIG=${BASE_PATH}/deepspeed.json +DATASET_1="./tmp/data/bookcorpus_train_1m_text_sentence" +DATASET="1 ${DATASET_1}" +CHECKPOINT_PATH=./tmp +TOKENIZER_PATH=./tmp/tokenizer.model # offical llama tokenizer.model + +TP=2 +PP=2 +ZERO_STAGE=0 + +GPUS_PER_NODE=8 +MASTER_ADDR=localhost +MASTER_PORT=6000 +NNODES=1 +NODE_RANK=0 + +HIDDEN_SIZE=2048 # e.g. llama-13b: 5120 +FFN_HIDDEN_SIZE=5504 # e.g. llama-13b: 13824 +NUM_LAYERS=24 # e.g. llama-13b: 40 +NUM_HEADS=16 # e.g. llama-13b: 40 +SEQ_LENGTH=2048 + +MICRO_BATCH_SIZE=4 +GLOBAL_BATCH_SIZE=32 # e.g. llama: 4M tokens +TRAIN_STEPS=250000 # e.g. llama: 1T tokens / 4M tokens_per_batch = 250000 steps +LR=3e-4 +MIN_LR=3e-5 +LR_WARMUP_STEPS=2000 +WEIGHT_DECAY=0.1 +GRAD_CLIP=1 + +## Activation checkpointing saves GPU memory, but reduces training speed +# activation_checkpoint="true" +activation_checkpoint="false" + +# Below configuration required for llama model as per llama paper +# --no-query-key-layer-scaling \ +# --attention-dropout 0 \ +# --hidden-dropout 0 \ +# --use-rotary-position-embeddings \ +# --untie-embeddings-and-output-weights \ +# --swiglu \ +# --normalization rmsnorm \ +# --disable-bias-linear \ +###################################### + + + +cat < $DS_CONFIG +{ + "train_batch_size" : $GLOBAL_BATCH_SIZE, + "train_micro_batch_size_per_gpu": $MICRO_BATCH_SIZE, + "steps_per_print": 1, + "zero_optimization": { + "stage": $ZERO_STAGE + }, + "bf16": { + "enabled": true + } +} +EOT + +ds_args="" +ds_args=" --deepspeed ${ds_args}" +ds_args=" --deepspeed_config=$DS_CONFIG ${ds_args}" +ds_args=" --zero-stage=$ZERO_STAGE ${ds_args}" + +if [ "${activation_checkpoint}" = "true" ]; then + ds_args="--deepspeed-activation-checkpointing ${ds_args}" + + ## old argument for recomputing the transformer layer + # ds_args="--checkpoint-activations ${ds_args}" + + ## new argument for recomputing the transformer layer + ds_args="--recompute-granularity full --recompute-method uniform ${ds_args}" + ## new argument for recomputing only the attention layer + # ds_args="--recompute-granularity selective ${ds_args}" +fi + +DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT" + +torchrun $DISTRIBUTED_ARGS \ + pretrain_gpt.py \ + --tensor-model-parallel-size $TP \ + --pipeline-model-parallel-size $PP \ + --num-layers $NUM_LAYERS \ + --hidden-size $HIDDEN_SIZE \ + --ffn-hidden-size $FFN_HIDDEN_SIZE \ + --num-attention-heads $NUM_HEADS \ + --micro-batch-size $MICRO_BATCH_SIZE \ + --global-batch-size $GLOBAL_BATCH_SIZE \ + --seq-length $SEQ_LENGTH \ + --max-position-embeddings $SEQ_LENGTH \ + --train-iters $TRAIN_STEPS \ + --save $CHECKPOINT_PATH \ + --load $CHECKPOINT_PATH \ + --data-path $DATASET \ + --data-impl mmap \ + --tokenizer-type GPTSentencePieceTokenizer \ + --tokenizer-model $TOKENIZER_PATH \ + --split 949,50,1 \ + --distributed-backend nccl \ + --lr $LR \ + --lr-decay-style cosine \ + --min-lr $MIN_LR \ + --weight-decay $WEIGHT_DECAY \ + --clip-grad $GRAD_CLIP \ + --lr-warmup-iters $LR_WARMUP_STEPS \ + --optimizer adam \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --log-interval 1 \ + --save-interval 10000 \ + --eval-interval 1000 \ + --eval-iters 10 \ + --bf16 \ + --no-query-key-layer-scaling \ + --attention-dropout 0 \ + --hidden-dropout 0 \ + --use-rotary-position-embeddings \ + --untie-embeddings-and-output-weights \ + --swiglu \ + --normalization rmsnorm \ + --disable-bias-linear \ + $ds_args \ No newline at end of file diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/rebase/ds_config_gpt_TEMPLATE.json b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/rebase/ds_config_gpt_TEMPLATE.json new file mode 100644 index 0000000000000000000000000000000000000000..3526aae85f0465ff7ec017f70b3e145d651da2f2 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/rebase/ds_config_gpt_TEMPLATE.json @@ -0,0 +1,23 @@ +{ + "train_batch_size": GBSIZE, + "train_micro_batch_size_per_gpu": MBSIZE, + "steps_per_print": LOG_INTERVAL, + + "zero_optimization": { + "stage": ZERO_STAGE + }, + + "gradient_clipping": 1.0, + "prescale_gradients": PRESCALE_GRAD, + + "fp16": { + "enabled": true, + "loss_scale": 0, + "loss_scale_window": 500, + "hysteresis": 2, + "min_loss_scale": 1, + "initial_scale_power": 11 + }, + + "wall_clock_breakdown" : false +} diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/rebase/ds_pretrain_gpt_1.3B_megatron_checkpointing.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/rebase/ds_pretrain_gpt_1.3B_megatron_checkpointing.sh new file mode 100644 index 0000000000000000000000000000000000000000..343dc9f0e8079858fd64218669ee42307296d6d1 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/rebase/ds_pretrain_gpt_1.3B_megatron_checkpointing.sh @@ -0,0 +1,345 @@ +#!/bin/bash +############################################################################### +############################################################################### +############################################################################### +## WARNING: This script is only for evaluating Megatron-LM's activation +## checkpointing. We do not recommend using it for actual training because +## you are not able to use any DeepSpeed technologies. +############################################################################### +############################################################################### +############################################################################### +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 + +## init_std is 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) + +## We changed min_lr to a lower number (1.0e-6), which we found is able to +## provide better zero-shot eval results. + +## 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=1.0e-6 +# init_std=0.02 + +## 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=1.0e-6 +# init_std=0.018 + +## 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=1.0e-6 +# init_std=0.015 + +## 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=1.0e-6 +init_std=0.013 + +## 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.0e-6 +# init_std=0.011 + +## 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.0e-6 +# init_std=0.009 + +## 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-6 +# init_std=0.008 + +## 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=1.0e-6 +# init_std=0.005 +############################################################################### +### Training duration configs +## The main termination condition, original GPT-3 paper trains for 300B tokens. +train_tokens_in_billion=300 +train_tokens=$((${train_tokens_in_billion} * 1000000000)) + +## 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 data efficiency techniques may change num tokens 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=$(( 300 * 1000000000 * 2 / ${seq_len} )) + +## Another wall-clock time termination condition in minutes. Set it large +## enough to avoid undesired early termination. +exit_duration=30000000 +############################################################################### +### lr configs +## lr warmup and decay duration. +## Original GPT-3 paper uses 375M warmup tokens and 260B cosine decay tokens. +## Here we increase the warmup tokens to 3B since when batch size warmup is not +## used, there are more tokens per step. Thus we need to increase warmup tokens +## to make sure there are enough warmup steps, which is important for training +## stability. +lr_warmup_tokens_in_million=3000 +lr_warmup_tokens=$((${lr_warmup_tokens_in_million} * 1000000)) +## Here we changed the LR decay tokens to align with total train tokens, since +## related works (e.g., https://arxiv.org/abs/2203.15556) find that setting the +## learning rate schedule to match the number of training tokens results in the +## best final model quality +lr_decay_tokens_in_billion=${train_tokens_in_billion} +lr_decay_tokens=$((${lr_decay_tokens_in_billion} * 1000000000)) +lr_decay_style="cosine" +############################################################################### +### Parallelism configs +## Model parallelism, 1 is no MP +mp_size=2 + +## Pipeline parallelism. To disable PP, set pp_size to 1 and no_pp to true. +## Note that currently both curriculum learning and random-LTD are NOT +## compatible with pipeline parallelism. +pp_size=1 +no_pp="true" + +## ZeRO-based data parallelism, stage=0 will disable ZeRO +zero_stage=0 + +## Total number of GPUs. ds_ssh is from DeepSpeed library. +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} )) + +## Data parallel size. +dp_size=$(( ${num_gpus} / ${pp_size} / ${mp_size} )) + +## Micro batch size per GPU +## Make sure that batch_size <= global_batch_size*pp_size*mp_size/num_gpus +## Reduce it manually if GPU OOM +# batch_size=$(( ${global_batch_size} / ${dp_size} )) +batch_size=2 +############################################################################### +### Misc configs +log_interval=10 +eval_iters=10 +eval_interval=100 +# num_save controls how frequent to save checkpoint. num_save=20 means that a +# checkpoint will be saved every 5% of training. For longer training you would +# want larger num_save to save more frequently, and vice versa. +num_save=100 +estimated_train_iter=$((${train_tokens} / ${seq_len} / ${global_batch_size})) +# save_interval=$((${estimated_train_iter} / ${num_save})) +save_interval=100 + +## 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}" +seed=1234 +num_workers=0 + +## Public the Pile dataset, can be downloaded at +## https://mystic.the-eye.eu/public/AI/pile_neox/ or +## https://the-eye.eu/public/AI/pile_neox/ Change data_home to where you +## store the pile_text_document.bin and pile_text_document.idx. +data_home="/vc_data_blob/users/conglli/the_pile_public_merged_nopreprocessing" +data_path="${data_home}/pile_text_document" + +vocab_path="gpt2-vocab.json" +if [ ! -f "$vocab_path" ]; then + wget https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-vocab.json +fi +merge_path="gpt2-merges.txt" +if [ ! -f "$merge_path" ]; then + wget https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-merges.txt +fi + +prescale_grad="true" +jobname="gpt_${model_size}B_tok${train_tokens_in_billion}B" +jobname="${jobname}_lr${lr}_min${min_lr}_w${lr_warmup_tokens_in_million}M_d${lr_decay_tokens_in_billion}B_${lr_decay_style}" +jobname="${jobname}_gbs${global_batch_size}_mbs${batch_size}_g${num_gpus}" +if [[ $zero_stage -gt 0 ]]; then + jobname="${jobname}_z${zero_stage}" + prescale_grad="false" +fi +if [[ $mp_size -gt 1 ]]; then + jobname="${jobname}_mp${mp_size}" +fi +if [ "${no_pp}" = "false" ]; then + jobname="${jobname}_pp${pp_size}" +fi +jobname="${jobname}_seed${seed}_rebase_megatron_checkpointing" + +username=$(whoami) +output_home="/blob/users/${username}/project/data_efficient_gpt" +log_path="${output_home}/log/" +checkpoint_path="${output_home}/checkpoint/${jobname}" +## Microsoft internal constraint: because tensorboard is logged by last rank, +## it's better to put the path in NFS instead of Blob. +tensorboard_dir="/vc_data/users/${username}/project/data_efficient_gpt/tensorboard/" +tensorboard_path="${tensorboard_dir}${jobname}_${host}_${current_time}" +mkdir -p ${log_path} +mkdir -p ${checkpoint_path} +mkdir -p ${tensorboard_path} +############################################################################### +data_options=" \ + --vocab-file ${vocab_path} \ + --merge-file ${merge_path} \ + --data-path ${data_path} \ + --data-impl mmap" + +## If CL is used, make sure to set "--split" the same as what you used during +## offline data analysis&indexing. +megatron_options=" \ + --override-opt_param-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 ${lr_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 ${lr_decay_style} \ + --split 949,50,1 \ + --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 ${num_workers} \ + --fp16 \ + --seed ${seed} \ + --load ${checkpoint_path} \ + --save ${checkpoint_path} \ + --no-async-tensor-model-parallel-allreduce \ + --tensorboard-queue-size 1 \ + --log-timers-to-tensorboard \ + --log-batch-size-to-tensorboard \ + --log-validation-ppl-to-tensorboard \ + --tensorboard-dir ${tensorboard_path}" + +# test megatron activation checkpointing +# we fixed bug in the code of this activation checkpointing, i.e., --recompute-granularity full --recompute-method uniform +# the two arguments can be found in megatron/arguments.py +if [ "${activation_checkpoint}" = "true" ]; then +megatron_options="${megatron_options} \ + --recompute-granularity full \ + --recompute-method uniform \ + --recompute-num-layers 1" +fi + +if [ "${log_optimizer_state}" = "true" ]; then +megatron_options="${megatron_options} \ + --log-optimizer-states-to-tensorboard" +fi + +config_json="ds_config_gbs${global_batch_size}_mbs${batch_size}_log${log_interval}_zero${zero_stage}.json" +template_json="ds_config_gpt_TEMPLATE.json" +sed "s/GBSIZE/${global_batch_size}/" ${template_json} \ + | sed "s/MBSIZE/${batch_size}/" \ + | sed "s/LOG_INTERVAL/${log_interval}/" \ + | sed "s/ZERO_STAGE/${zero_stage}/" \ + | sed "s/PRESCALE_GRAD/${prescale_grad}/" \ + > ${config_json} + +deepspeed_options=" \ + --pipeline-model-parallel-size ${pp_size}" + +if [[ "${no_pp}" = "true" ]]; then +deepspeed_options="${deepspeed_options} \ + --no-pipeline-parallel" +fi + +# disable the deepspeed activation checkpointing + +# 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 + +deepspeed ${dir}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &>> ${log_path}/${jobname}_${host}_${current_time}.log diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/rebase/ds_pretrain_gpt_125M.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/rebase/ds_pretrain_gpt_125M.sh new file mode 100644 index 0000000000000000000000000000000000000000..8235b6c1aeeee408f552b5e7e041d85f6e721ac2 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/rebase/ds_pretrain_gpt_125M.sh @@ -0,0 +1,331 @@ +#!/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 + +## init_std is 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) + +## We changed min_lr to a lower number (1.0e-6), which we found is able to +## provide better zero-shot eval results. + +## 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=1.0e-6 +init_std=0.02 + +## 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=1.0e-6 +# init_std=0.018 + +## 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=1.0e-6 +# init_std=0.015 + +## 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=1.0e-6 +# init_std=0.013 + +## 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.0e-6 +# init_std=0.011 + +## 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.0e-6 +# init_std=0.009 + +## 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-6 +# init_std=0.008 + +## 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=1.0e-6 +# init_std=0.005 +############################################################################### +### Training duration configs +## The main termination condition, original GPT-3 paper trains for 300B tokens. +train_tokens_in_billion=300 +train_tokens=$((${train_tokens_in_billion} * 1000000000)) + +## 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 data efficiency techniques may change num tokens 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=$(( 300 * 1000000000 * 2 / ${seq_len} )) + +## Another wall-clock time termination condition in minutes. Set it large +## enough to avoid undesired early termination. +exit_duration=30000000 +############################################################################### +### lr configs +## lr warmup and decay duration. +## Original GPT-3 paper uses 375M warmup tokens and 260B cosine decay tokens. +## Here we increase the warmup tokens to 3B since when batch size warmup is not +## used, there are more tokens per step. Thus we need to increase warmup tokens +## to make sure there are enough warmup steps, which is important for training +## stability. +lr_warmup_tokens_in_million=3000 +lr_warmup_tokens=$((${lr_warmup_tokens_in_million} * 1000000)) +## Here we changed the LR decay tokens to align with total train tokens, since +## related works (e.g., https://arxiv.org/abs/2203.15556) find that setting the +## learning rate schedule to match the number of training tokens results in the +## best final model quality +lr_decay_tokens_in_billion=${train_tokens_in_billion} +lr_decay_tokens=$((${lr_decay_tokens_in_billion} * 1000000000)) +lr_decay_style="cosine" +############################################################################### +### Parallelism configs +## Model parallelism, 1 is no MP +mp_size=2 + +## Pipeline parallelism. To disable PP, set pp_size to 1 and no_pp to true. +## Note that currently both curriculum learning and random-LTD are NOT +## compatible with pipeline parallelism. +pp_size=2 +no_pp="false" + +## ZeRO-based data parallelism, stage=0 will disable ZeRO +zero_stage=1 + +## Total number of GPUs. ds_ssh is from DeepSpeed library. +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} )) + +## Data parallel size. +dp_size=$(( ${num_gpus} / ${pp_size} / ${mp_size} )) + +## Micro batch size per GPU +## Make sure that batch_size <= global_batch_size*pp_size*mp_size/num_gpus +## Reduce it manually if GPU OOM +# batch_size=$(( ${global_batch_size} / ${dp_size} )) +batch_size=2 +############################################################################### +### Misc configs +log_interval=10 +eval_iters=10 +eval_interval=100 +# num_save controls how frequent to save checkpoint. num_save=20 means that a +# checkpoint will be saved every 5% of training. For longer training you would +# want larger num_save to save more frequently, and vice versa. +num_save=100 +estimated_train_iter=$((${train_tokens} / ${seq_len} / ${global_batch_size})) +# save_interval=$((${estimated_train_iter} / ${num_save})) +save_interval=100 + +## 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}" +seed=1234 +num_workers=0 + +data_path="BookCorpusDataset_text_document" +if [ ! -f "BookCorpusDataset_text_document.bin" ]; then + wget https://the-eye.eu/public/AI/pile_neox/data/BookCorpusDataset_text_document.bin +fi +if [ ! -f "BookCorpusDataset_text_document.idx" ]; then + wget https://the-eye.eu/public/AI/pile_neox/data/BookCorpusDataset_text_document.idx +fi + +vocab_path="gpt2-vocab.json" +if [ ! -f "$vocab_path" ]; then + wget https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-vocab.json +fi +merge_path="gpt2-merges.txt" +if [ ! -f "$merge_path" ]; then + wget https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-merges.txt +fi + +prescale_grad="true" +jobname="gpt_${model_size}B_tok${train_tokens_in_billion}B" +jobname="${jobname}_lr${lr}_min${min_lr}_w${lr_warmup_tokens_in_million}M_d${lr_decay_tokens_in_billion}B_${lr_decay_style}" +jobname="${jobname}_gbs${global_batch_size}_mbs${batch_size}_g${num_gpus}" +if [[ $zero_stage -gt 0 ]]; then + jobname="${jobname}_z${zero_stage}" + prescale_grad="false" +fi +if [[ $mp_size -gt 1 ]]; then + jobname="${jobname}_mp${mp_size}" +fi +if [ "${no_pp}" = "false" ]; then + jobname="${jobname}_pp${pp_size}" +fi +jobname="${jobname}_seed${seed}_rebase" + +username=$(whoami) +output_home="output" +log_path="${output_home}/log/" +checkpoint_path="${output_home}/checkpoint/${jobname}" +tensorboard_dir="${output_home}/tensorboard/" +tensorboard_path="${tensorboard_dir}${jobname}_${host}_${current_time}" +mkdir -p ${log_path} +mkdir -p ${checkpoint_path} +mkdir -p ${tensorboard_path} +############################################################################### +data_options=" \ + --vocab-file ${vocab_path} \ + --merge-file ${merge_path} \ + --data-path ${data_path} \ + --data-impl mmap" + +## If CL is used, make sure to set "--split" the same as what you used during +## offline data analysis&indexing. +megatron_options=" \ + --override-opt_param-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 ${lr_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 ${lr_decay_style} \ + --split 949,50,1 \ + --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 ${num_workers} \ + --fp16 \ + --seed ${seed} \ + --load ${checkpoint_path} \ + --save ${checkpoint_path} \ + --no-async-tensor-model-parallel-allreduce \ + --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 + +config_json="ds_config_gbs${global_batch_size}_mbs${batch_size}_log${log_interval}_zero${zero_stage}.json" +template_json="ds_config_gpt_TEMPLATE.json" +sed "s/GBSIZE/${global_batch_size}/" ${template_json} \ + | sed "s/MBSIZE/${batch_size}/" \ + | sed "s/LOG_INTERVAL/${log_interval}/" \ + | sed "s/ZERO_STAGE/${zero_stage}/" \ + | sed "s/PRESCALE_GRAD/${prescale_grad}/" \ + > ${config_json} + +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 + +deepspeed ${dir}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &>> ${log_path}/${jobname}_${host}_${current_time}.log \ No newline at end of file diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/rebase/ds_pretrain_gpt_13B.sh b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/rebase/ds_pretrain_gpt_13B.sh new file mode 100644 index 0000000000000000000000000000000000000000..931886b34d8d2402059e24d3f5f4ddaf99a00fcf --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/examples_deepspeed/rebase/ds_pretrain_gpt_13B.sh @@ -0,0 +1,332 @@ +#!/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 + +## init_std is 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) + +## We changed min_lr to a lower number (1.0e-6), which we found is able to +## provide better zero-shot eval results. + +## 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=1.0e-6 +# init_std=0.02 + +## 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=1.0e-6 +# init_std=0.018 + +## 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=1.0e-6 +# init_std=0.015 + +## 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=1.0e-6 +# init_std=0.013 + +## 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.0e-6 +# init_std=0.011 + +## 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.0e-6 +# init_std=0.009 + +## 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-6 +init_std=0.008 + +## 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=1.0e-6 +# init_std=0.005 +############################################################################### +### Training duration configs +## The main termination condition, original GPT-3 paper trains for 300B tokens. +train_tokens_in_billion=300 +train_tokens=$((${train_tokens_in_billion} * 1000000000)) + +## 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 data efficiency techniques may change num tokens 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=$(( 300 * 1000000000 * 2 / ${seq_len} )) + +## Another wall-clock time termination condition in minutes. Set it large +## enough to avoid undesired early termination. +exit_duration=30000000 +############################################################################### +### lr configs +## lr warmup and decay duration. +## Original GPT-3 paper uses 375M warmup tokens and 260B cosine decay tokens. +## Here we increase the warmup tokens to 3B since when batch size warmup is not +## used, there are more tokens per step. Thus we need to increase warmup tokens +## to make sure there are enough warmup steps, which is important for training +## stability. +lr_warmup_tokens_in_million=3000 +lr_warmup_tokens=$((${lr_warmup_tokens_in_million} * 1000000)) +## Here we changed the LR decay tokens to align with total train tokens, since +## related works (e.g., https://arxiv.org/abs/2203.15556) find that setting the +## learning rate schedule to match the number of training tokens results in the +## best final model quality +lr_decay_tokens_in_billion=${train_tokens_in_billion} +lr_decay_tokens=$((${lr_decay_tokens_in_billion} * 1000000000)) +lr_decay_style="cosine" +############################################################################### +### Parallelism configs +## Model parallelism, 1 is no MP +mp_size=4 + +## Pipeline parallelism. To disable PP, set pp_size to 1 and no_pp to true. +## Note that currently both curriculum learning and random-LTD are NOT +## compatible with pipeline parallelism. +pp_size=8 +no_pp="false" + +## ZeRO-based data parallelism, stage=0 will disable ZeRO +zero_stage=1 + +## Total number of GPUs. ds_ssh is from DeepSpeed library. +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} )) + +## Data parallel size. +dp_size=$(( ${num_gpus} / ${pp_size} / ${mp_size} )) + +## Micro batch size per GPU +## Make sure that batch_size <= global_batch_size*pp_size*mp_size/num_gpus +## Reduce it manually if GPU OOM +# batch_size=$(( ${global_batch_size} / ${dp_size} )) +batch_size=2 +############################################################################### +### Misc configs +log_interval=10 +eval_iters=10 +eval_interval=100 +# num_save controls how frequent to save checkpoint. num_save=20 means that a +# checkpoint will be saved every 5% of training. For longer training you would +# want larger num_save to save more frequently, and vice versa. +num_save=100 +estimated_train_iter=$((${train_tokens} / ${seq_len} / ${global_batch_size})) +# save_interval=$((${estimated_train_iter} / ${num_save})) +save_interval=100 + +## 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}" +seed=1234 +num_workers=0 + +## Public the Pile dataset, can be downloaded at +## https://mystic.the-eye.eu/public/AI/pile_neox/ or +## https://the-eye.eu/public/AI/pile_neox/ Change data_home to where you +## store the pile_text_document.bin and pile_text_document.idx. +data_home="/vc_data_blob/users/conglli/the_pile_public_merged_nopreprocessing" +data_path="${data_home}/pile_text_document" + +vocab_path="gpt2-vocab.json" +if [ ! -f "$vocab_path" ]; then + wget https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-vocab.json +fi +merge_path="gpt2-merges.txt" +if [ ! -f "$merge_path" ]; then + wget https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-merges.txt +fi + +prescale_grad="true" +jobname="gpt_${model_size}B_tok${train_tokens_in_billion}B" +jobname="${jobname}_lr${lr}_min${min_lr}_w${lr_warmup_tokens_in_million}M_d${lr_decay_tokens_in_billion}B_${lr_decay_style}" +jobname="${jobname}_gbs${global_batch_size}_mbs${batch_size}_g${num_gpus}" +if [[ $zero_stage -gt 0 ]]; then + jobname="${jobname}_z${zero_stage}" + prescale_grad="false" +fi +if [[ $mp_size -gt 1 ]]; then + jobname="${jobname}_mp${mp_size}" +fi +if [ "${no_pp}" = "false" ]; then + jobname="${jobname}_pp${pp_size}" +fi +jobname="${jobname}_seed${seed}_rebase" + +username=$(whoami) +output_home="/blob/users/${username}/project/data_efficient_gpt" +log_path="${output_home}/log/" +checkpoint_path="${output_home}/checkpoint/${jobname}" +## Microsoft internal constraint: because tensorboard is logged by last rank, +## it's better to put the path in NFS instead of Blob. +tensorboard_dir="/vc_data/users/${username}/project/data_efficient_gpt/tensorboard/" +tensorboard_path="${tensorboard_dir}${jobname}_${host}_${current_time}" +mkdir -p ${log_path} +mkdir -p ${checkpoint_path} +mkdir -p ${tensorboard_path} +############################################################################### +data_options=" \ + --vocab-file ${vocab_path} \ + --merge-file ${merge_path} \ + --data-path ${data_path} \ + --data-impl mmap" + +## If CL is used, make sure to set "--split" the same as what you used during +## offline data analysis&indexing. +megatron_options=" \ + --override-opt_param-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 ${lr_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 ${lr_decay_style} \ + --split 949,50,1 \ + --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 ${num_workers} \ + --fp16 \ + --seed ${seed} \ + --load ${checkpoint_path} \ + --save ${checkpoint_path} \ + --no-async-tensor-model-parallel-allreduce \ + --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 + +config_json="ds_config_gbs${global_batch_size}_mbs${batch_size}_log${log_interval}_zero${zero_stage}.json" +template_json="ds_config_gpt_TEMPLATE.json" +sed "s/GBSIZE/${global_batch_size}/" ${template_json} \ + | sed "s/MBSIZE/${batch_size}/" \ + | sed "s/LOG_INTERVAL/${log_interval}/" \ + | sed "s/ZERO_STAGE/${zero_stage}/" \ + | sed "s/PRESCALE_GRAD/${prescale_grad}/" \ + > ${config_json} + +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 + +deepspeed ${dir}/../../pretrain_gpt.py ${megatron_options} ${data_options} ${deepspeed_options} &>> ${log_path}/${jobname}_${host}_${current_time}.log \ No newline at end of file diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/images/Achieved_petaFLOPs.png b/docker/intel_code/llama13b/Megatron-DeepSpeed/images/Achieved_petaFLOPs.png new file mode 100644 index 0000000000000000000000000000000000000000..7505fd42942ac210472b0c04391e047109ce87f9 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/images/Achieved_petaFLOPs.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3856991d81046b3da4af85b5fce7f0a61ed3f2b643358b8366c9bd22534ae85c +size 229267 diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/images/cases_april2021.png b/docker/intel_code/llama13b/Megatron-DeepSpeed/images/cases_april2021.png new file mode 100644 index 0000000000000000000000000000000000000000..9b70f655a7d887e799ef5e3a33b773df7451d8ee --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/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/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/__init__.cpython-310.pyc b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d231da6cbf4b3b03cb9f25256591f0bd9a7c7be4 Binary files /dev/null and b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/__init__.cpython-310.pyc differ diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/bert_model.cpython-310.pyc b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/bert_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af9ec9b457805766a63ea6f7718c6d3d85f4b7da Binary files /dev/null and b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/bert_model.cpython-310.pyc differ diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/distributed.cpython-310.pyc b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/distributed.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4b5138300b9b3ff0527bb8329f72c9584e25b1d Binary files /dev/null and b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/distributed.cpython-310.pyc differ diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/enums.cpython-310.pyc b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/enums.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0fd9ec8b15051a0e7bd2f272d1b7e4bd2bc5b866 Binary files /dev/null and b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/enums.cpython-310.pyc differ diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/fused_bias_gelu.cpython-310.pyc b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/fused_bias_gelu.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c86bb931abaf1679f268e145d71a44d6b6c0ef7 Binary files /dev/null and b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/fused_bias_gelu.cpython-310.pyc differ diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/fused_layer_norm.cpython-310.pyc b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/fused_layer_norm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44c80f0aad807a844ae060d6dd444db66d09745f Binary files /dev/null and b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/fused_layer_norm.cpython-310.pyc differ diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/fused_softmax.cpython-310.pyc b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/fused_softmax.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2420b0842d1614b4e8d29c5e0ba1515e92f39326 Binary files /dev/null and b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/fused_softmax.cpython-310.pyc differ diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/gpt_model.cpython-310.pyc b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/gpt_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56c3c168de0d8a78aba9e221198caa9626da9c71 Binary files /dev/null and b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/gpt_model.cpython-310.pyc differ diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/language_model.cpython-310.pyc b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/language_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e5efba16ec07893888bc06e56c99e2373154369 Binary files /dev/null and b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/language_model.cpython-310.pyc differ diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/module.cpython-310.pyc b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/module.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bb3283acb943a36cc286441b499ef82d4f37e4f Binary files /dev/null and b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/module.cpython-310.pyc differ diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/rmsnorm.cpython-310.pyc b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/rmsnorm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62a36291bb07509d47424f6e8dc203b88d56c44f Binary files /dev/null and b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/rmsnorm.cpython-310.pyc differ diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/rotary_pos_embedding.cpython-310.pyc b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/rotary_pos_embedding.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b6b08b9729e411b8eb827a04160a1d687fdfd6d Binary files /dev/null and b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/rotary_pos_embedding.cpython-310.pyc differ diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/t5_model.cpython-310.pyc b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/t5_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a4947709f021d4eabc3f18d968dc5c9fdff196d Binary files /dev/null and b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/t5_model.cpython-310.pyc differ diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/transformer.cpython-310.pyc b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/transformer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b061095cac3e20c61165bfd44f61047f3bf5e27 Binary files /dev/null and b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/transformer.cpython-310.pyc differ diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/utils.cpython-310.pyc b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a728204df660719e0a42fd4131a62a04550fa9b7 Binary files /dev/null and b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/__pycache__/utils.cpython-310.pyc differ diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/fused_layer_norm.py b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/fused_layer_norm.py new file mode 100644 index 0000000000000000000000000000000000000000..73b4ed60f78ea02dd4f3a342901583714b17877d --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/fused_layer_norm.py @@ -0,0 +1,119 @@ +# Copyright (C) 2024 Habana Labs, Ltd. an Intel Company. +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. + +"""This code is copied fron NVIDIA apex: + https://github.com/NVIDIA/apex + with some changes. """ + +import numbers +import torch +from torch.nn.parameter import Parameter +from torch.nn import init +import importlib +from torch.nn import functional as F +import inspect + +from megatron.core.utils import make_viewless_tensor +from megatron import get_args + +from deepspeed.accelerator.real_accelerator import get_accelerator + +try: + from apex.contrib.layer_norm.layer_norm import FastLayerNormFN + HAVE_PERSIST_LAYER_NORM = True +except: + HAVE_PERSIST_LAYER_NORM = False + +try: + from apex.normalization.fused_layer_norm import FusedLayerNormAffineFunction +except ModuleNotFoundError: + pass + + +global fused_layer_norm_cuda +fused_layer_norm_cuda = None + + +class MixedFusedLayerNorm(torch.nn.Module): + + def __init__(self, normalized_shape, eps=1e-5, + no_persist_layer_norm=True, + sequence_parallel=False, + apply_layernorm_1p=False, + mem_efficient_ln=True): + super(MixedFusedLayerNorm, self).__init__() + + self.apply_layernorm_1p = apply_layernorm_1p + self.mem_efficient_ln = mem_efficient_ln + + if get_accelerator().device_name() == 'cuda': + global fused_layer_norm_cuda + fused_layer_norm_cuda = importlib.import_module("fused_layer_norm_cuda") + + # List of hiddens sizes supported in the persistent layer norm kernel + # If the hidden size is not supported, fall back to the non-persistent + # kernel. + persist_ln_hidden_sizes = [1024, 1536, 2048, 2304, 3072, 3840, 4096, + 5120, 6144, 8192, 10240, 12288, 12800, 15360, 16384, 18432, 20480, + 24576, 25600, 30720, 32768, 40960, 49152, 65536] + if normalized_shape not in persist_ln_hidden_sizes or \ + not HAVE_PERSIST_LAYER_NORM: + no_persist_layer_norm = True + + if isinstance(normalized_shape, numbers.Integral): + normalized_shape = (normalized_shape,) + self.normalized_shape = torch.Size(normalized_shape) + self.eps = eps + self.weight = Parameter(torch.empty(*normalized_shape, + device=get_accelerator().current_device_name(), + dtype=get_args().params_dtype)) + self.bias = Parameter(torch.empty(*normalized_shape, + device=get_accelerator().current_device_name(), + dtype=get_args().params_dtype)) + self.reset_parameters() + self.no_persist_layer_norm = no_persist_layer_norm + self.sequence_parallel = sequence_parallel + + # set sequence parallelism flag on weight and bias parameters + setattr(self.weight, 'sequence_parallel', self.sequence_parallel) + setattr(self.bias, 'sequence_parallel', self.sequence_parallel) + + + def reset_parameters(self): + + if self.apply_layernorm_1p: + init.zeros_(self.weight) + init.zeros_(self.bias) + else: + init.ones_(self.weight) + init.zeros_(self.bias) + + def forward(self, input): + + weight = self.weight + 1 if self.apply_layernorm_1p else self.weight + # CPU path is here for unittest sake. + if not input.is_cuda: + if get_accelerator().device_name() == 'cuda': + print("WARNING! The input of FusedLayerNorm should be on the GPU." + "This warning should only be triggered in the FusedLayerNorm unit tests.") + return F.layer_norm(input, self.normalized_shape, weight, self.bias, self.eps) + + if self.no_persist_layer_norm: + # Apex does not have versions yet (https://github.com/NVIDIA/apex/pull/1648), so we need to inspect + # the function manually on whether the extra arg introduced in https://github.com/NVIDIA/apex/pull/1715 exists yet + if 'memory_efficient' in inspect.getfullargspec(FusedLayerNormAffineFunction.forward).args: + return FusedLayerNormAffineFunction.apply(input, weight, self.bias, self.normalized_shape, self.eps, self.mem_efficient_ln) + else: + return FusedLayerNormAffineFunction.apply(input, weight, self.bias, self.normalized_shape, self.eps) + else: + output = FastLayerNormFN.apply(input, weight, self.bias, self.eps) + + # Apex's fast layer norm function outputs a 'view' tensor (i.e., has + # a populated '_base' field). This will result in schedule.py's + # deallocate_output_tensor() throwing an error, so a viewless tensor is + # created to prevent this. + output = make_viewless_tensor(inp = output, + requires_grad = input.requires_grad, + keep_graph = True) + + return output diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/fused_softmax.py b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/fused_softmax.py new file mode 100644 index 0000000000000000000000000000000000000000..2fe61d4073862c5bccb15c62ed9e62bd91ec69ea --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/fused_softmax.py @@ -0,0 +1,213 @@ +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. + + +import torch +import torch.nn as nn +from megatron.model.enums import AttnMaskType + + +class ScaledUpperTriangMaskedSoftmax(torch.autograd.Function): + """ + Fused operation which performs following three operations in sequence + 1. Scale the tensor. + 2. Apply upper triangular mask (typically used in gpt models). + 3. Perform softmax. + """ + + @staticmethod + def forward(ctx, inputs, scale): + import scaled_upper_triang_masked_softmax_cuda + + scale_t = torch.tensor([scale]) + softmax_results = scaled_upper_triang_masked_softmax_cuda.forward( + inputs, scale_t[0] + ) + + ctx.save_for_backward(softmax_results, scale_t) + return softmax_results + + @staticmethod + def backward(ctx, output_grads): + import scaled_upper_triang_masked_softmax_cuda + + softmax_results, scale_t = ctx.saved_tensors + input_grads = scaled_upper_triang_masked_softmax_cuda.backward( + output_grads, softmax_results, scale_t[0] + ) + + return input_grads, None + + +class ScaledMaskedSoftmax(torch.autograd.Function): + """ + Fused operation which performs following three operations in sequence + 1. Scale the tensor. + 2. Apply the mask. + 3. Perform softmax. + """ + + @staticmethod + def forward(ctx, inputs, mask, scale): + import scaled_masked_softmax_cuda + + scale_t = torch.tensor([scale]) + + softmax_results = scaled_masked_softmax_cuda.forward(inputs, mask, scale_t[0]) + ctx.save_for_backward(softmax_results, scale_t) + return softmax_results + + @staticmethod + def backward(ctx, output_grads): + import scaled_masked_softmax_cuda + + softmax_results, scale_t = ctx.saved_tensors + + input_grads = scaled_masked_softmax_cuda.backward( + output_grads, softmax_results, scale_t[0] + ) + return input_grads, None, None + + +class ScaledSoftmax(torch.autograd.Function): + """ + Fused operation which performs following two operations in sequence + 1. Scale the tensor. + 2. Perform softmax. + """ + + @staticmethod + def forward(ctx, inputs, scale): + import scaled_softmax_cuda + + scale_t = torch.tensor([scale]) + + softmax_results = scaled_softmax_cuda.forward( + inputs, scale_t[0] + ) + ctx.save_for_backward(softmax_results, scale_t) + return softmax_results + + @staticmethod + def backward(ctx, output_grads): + import scaled_softmax_cuda + + softmax_results, scale_t = ctx.saved_tensors + + input_grads = scaled_softmax_cuda.backward( + output_grads, softmax_results, scale_t[0] + ) + return input_grads, None, None + + +class FusedScaleMaskSoftmax(nn.Module): + """ + fused operation: scaling + mask + softmax + + Arguments: + input_in_fp16: flag to indicate if input in fp16 data format. + input_in_bf16: flag to indicate if input in bf16 data format. + attn_mask_type: attention mask type (pad or causal) + scaled_masked_softmax_fusion: flag to indicate user want to use softmax fusion + mask_func: mask function to be applied. + softmax_in_fp32: if true, softmax in performed at fp32 precision. + scale: scaling factor used in input tensor scaling. + """ + + def __init__( + self, + input_in_fp16, + input_in_bf16, + attn_mask_type, + scaled_masked_softmax_fusion, + mask_func, + softmax_in_fp32, + scale, + ): + super(FusedScaleMaskSoftmax, self).__init__() + self.input_in_fp16 = input_in_fp16 + self.input_in_bf16 = input_in_bf16 + assert not ( + self.input_in_fp16 and self.input_in_bf16 + ), "both fp16 and bf16 flags cannot be active at the same time." + self.input_in_float16 = self.input_in_fp16 or self.input_in_bf16 + self.attn_mask_type = attn_mask_type + self.scaled_masked_softmax_fusion = scaled_masked_softmax_fusion + self.mask_func = mask_func + self.softmax_in_fp32 = softmax_in_fp32 + self.scale = scale + + assert ( + self.scale is None or softmax_in_fp32 + ), "softmax should be in fp32 when scaled" + + def forward(self, input, mask): + # [b, np, sq, sk] + assert input.dim() == 4 + + if self.is_kernel_available(mask, *input.size()): + return self.forward_fused_softmax(input, mask) + else: + return self.forward_torch_softmax(input, mask) + + def is_kernel_available(self, mask, b, np, sq, sk): + attn_batches = b * np + + if ( + self.scaled_masked_softmax_fusion # user want to fuse + and self.input_in_float16 # input must be fp16 + and 16 < sk <= 4096 # sk must be 16 ~ 2048 + and sq % 4 == 0 # sq must be divisor of 4 + and sk % 4 == 0 # sk must be divisor of 4 + and attn_batches % 4 == 0 # np * b must be divisor of 4 + ): + if 0 <= sk <= 4096: + batch_per_block = self.get_batch_per_block(sq, sk, b, np) + + if self.attn_mask_type.value == AttnMaskType.causal.value: + if attn_batches % batch_per_block == 0: + return True + else: + if sq % batch_per_block == 0: + return True + return False + + def forward_fused_softmax(self, input, mask): + b, np, sq, sk = input.size() + scale = self.scale if self.scale is not None else 1.0 + + if self.attn_mask_type.value == AttnMaskType.causal.value: + assert sq == sk, "causal mask is only for self attention" + + # input is 3D tensor (attn_batches, sq, sk) + input = input.view(-1, sq, sk) + probs = ScaledUpperTriangMaskedSoftmax.apply(input, scale) + return probs.view(b, np, sq, sk) + else: + # input is 4D tensor (b, np, sq, sk) + if mask is not None: + return ScaledMaskedSoftmax.apply(input, mask, scale) + else: + return ScaledSoftmax.apply(input, scale) + + def forward_torch_softmax(self, input, mask): + if self.input_in_float16 and self.softmax_in_fp32: + input = input.float() + + if self.scale is not None: + input = input * self.scale + mask_output = self.mask_func(input, mask) if mask is not None else input + probs = torch.nn.Softmax(dim=-1)(mask_output) + + if self.input_in_float16 and self.softmax_in_fp32: + if self.input_in_fp16: + probs = probs.half() + else: + probs = probs.bfloat16() + + return probs + + @staticmethod + def get_batch_per_block(sq, sk, b, np): + import scaled_masked_softmax_cuda + + return scaled_masked_softmax_cuda.get_batch_per_block(sq, sk, b, np) diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/language_model.py b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/language_model.py new file mode 100644 index 0000000000000000000000000000000000000000..41b0b7b98938c4ea242b99ffb2b56e6b83caa99f --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/language_model.py @@ -0,0 +1,723 @@ +# Copyright (C) 2024 Habana Labs, Ltd. an Intel Company. +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. + +"""Transformer based language model.""" + +import torch +import torch.nn.functional as F + +from megatron import get_args +from megatron.core import mpu, tensor_parallel +from megatron.core.enums import ModelType + +from .enums import AttnMaskType, LayerType +from .module import MegatronModule +from .rotary_pos_embedding import apply_rotary_pos_emb, RotaryEmbedding +from .transformer import ParallelTransformer +from .utils import get_linear_layer +from .utils import init_method_normal, scaled_init_method_normal, gather_and_init + + +def parallel_lm_logits(input_, word_embeddings_weight, parallel_output, + bias=None): + """LM logits using word embedding weights.""" + args = get_args() + # Parallel logits. + if args.async_tensor_model_parallel_allreduce or\ + args.sequence_parallel: + input_parallel = input_ + model_parallel = mpu.get_tensor_model_parallel_world_size() > 1 + async_grad_allreduce = args.async_tensor_model_parallel_allreduce and \ + model_parallel and not args.sequence_parallel + else: + input_parallel = tensor_parallel.copy_to_tensor_model_parallel_region(input_) + async_grad_allreduce = False + + # Matrix multiply. + logits_parallel = tensor_parallel.linear_with_grad_accumulation_and_async_allreduce( + input=input_parallel, + weight=word_embeddings_weight, + bias=bias, + gradient_accumulation_fusion=args.gradient_accumulation_fusion, + async_grad_allreduce=async_grad_allreduce, + sequence_parallel=args.sequence_parallel) + # Gather if needed. + + if parallel_output: + return logits_parallel + + return tensor_parallel.gather_from_tensor_model_parallel_region(logits_parallel) + + +def get_language_model(config, num_tokentypes, add_pooler, + encoder_attn_mask_type, + add_encoder=True, + add_decoder=False, + decoder_attn_mask_type=AttnMaskType.causal, + pre_process=True, post_process=True, num_experts=[1]): + """Build language model and return along with the key to save.""" + args = get_args() + if config.init_method is None: + config.init_method = init_method_normal(config.init_method_std) + + if config.output_layer_init_method is None: + config.output_layer_init_method = scaled_init_method_normal(config.init_method_std, + config.num_layers) + + # Language model. + language_model = TransformerLanguageModel( + config, + encoder_attn_mask_type, + num_tokentypes=num_tokentypes, + add_encoder=add_encoder, + add_decoder=add_decoder, + decoder_attn_mask_type=decoder_attn_mask_type, + add_pooler=add_pooler, + pre_process=pre_process, + post_process=post_process, + num_experts=num_experts) + # key used for checkpoints. + language_model_key = 'language_model' + + return language_model, language_model_key + + +class Pooler(MegatronModule): + """Pooler layer. + + Pool hidden states of a specific token (for example start of the + sequence) and add a linear transformation followed by a tanh. + + Arguments: + hidden_size: hidden size + init_method: weight initialization method for the linear layer. + bias is set to zero. + """ + + def __init__(self, hidden_size, init_method): + super(Pooler, self).__init__() + args = get_args() + self.dense = get_linear_layer(hidden_size, hidden_size, init_method, gather_params_on_init=args.zero_stage == 3) + self.sequence_parallel = args.sequence_parallel + + + def forward(self, hidden_states, sequence_index=0): + # hidden_states: [s, b, h] + # sequence_index: index of the token to pool. + + # gather data along sequence dimensions + # same pooler is run on all tensor parallel nodes + if self.sequence_parallel: + hidden_states = tensor_parallel.gather_from_sequence_parallel_region( + hidden_states, + tensor_parallel_output_grad=False) + + pooled = hidden_states[sequence_index, :, :] + pooled = self.dense(pooled) + pooled = torch.tanh(pooled) + return pooled + + +class Embedding(MegatronModule): + """Language model embeddings. + + Arguments: + hidden_size: hidden size + vocab_size: vocabulary size + max_sequence_length: maximum size of sequence. This + is used for positional embedding + embedding_dropout_prob: dropout probability for embeddings + init_method: weight initialization method + num_tokentypes: size of the token-type embeddings. 0 value + will ignore this embedding + embedding_weights_in_fp32: casts word embedding weights to + fp32 before sampling. Required to + maintain reproducibility when + training in bf16. + """ + + def __init__(self, + hidden_size, + vocab_size, + max_sequence_length, + embedding_dropout_prob, + config, + add_position_embedding=True, + num_tokentypes=0, + embedding_weights_in_fp32=False): + super(Embedding, self).__init__() + + self.hidden_size = hidden_size + self.init_method = config.init_method + self.num_tokentypes = num_tokentypes + + args = get_args() + + # Word embeddings (parallel). + self.embedding_weights_in_fp32 = embedding_weights_in_fp32 + self.params_dtype = args.params_dtype + self.word_embeddings = tensor_parallel.VocabParallelEmbedding( + vocab_size, self.hidden_size, config=config, init_method=config.init_method) + self._word_embeddings_key = 'word_embeddings' + + # Position embedding (serial). + self.add_position_embedding = add_position_embedding + if self.add_position_embedding: + self._position_embeddings_key = 'position_embeddings' + if args.sequence_parallel: + self.position_embeddings = tensor_parallel.layers.SequenceParallelPositionEmbedding( + max_sequence_length, self.hidden_size) + # Initialize the position embeddings. + self.init_method(self.position_embeddings.local_embeddings.weight) + else: + self.position_embeddings = torch.nn.Embedding( + max_sequence_length, self.hidden_size) + # Initialize the position embeddings. + if args.perform_initialization: + if args.zero_stage == 3: + gather_and_init(self.position_embeddings.weight, self.init_method) + else: + self.init_method(self.position_embeddings.weight) + + # Token type embedding. + # Add this as an optional field that can be added through + # method call so we can load a pretrain model without + # token types and add them as needed. + self._tokentype_embeddings_key = 'tokentype_embeddings' + if self.num_tokentypes > 0: + self.tokentype_embeddings = torch.nn.Embedding(self.num_tokentypes, + self.hidden_size) + # Initialize the token-type embeddings. + if args.perform_initialization: + if args.zero_stage == 3: + gather_and_init(self.tokentype_embeddings.weight, self.init_method) + else: + self.init_method(self.tokentype_embeddings.weight) + else: + self.tokentype_embeddings = None + + self.fp32_residual_connection = args.fp32_residual_connection + self.sequence_parallel = args.sequence_parallel + # Embeddings dropout + self.embedding_dropout = torch.nn.Dropout(embedding_dropout_prob) + + def zero_parameters(self): + """Zero out all parameters in embedding.""" + self.word_embeddings.weight.data.fill_(0) + self.word_embeddings.weight.shared = True + if self.add_position_embedding: + self.position_embeddings.weight.data.fill_(0) + self.position_embeddings.weight.shared = True + if self.num_tokentypes > 0: + self.tokentype_embeddings.weight.data.fill_(0) + self.tokentype_embeddings.weight.shared = True + + def add_tokentype_embeddings(self, num_tokentypes): + """Add token-type embedding. This function is provided so we can add + token-type embeddings in case the pretrained model does not have it. + This allows us to load the model normally and then add this embedding. + """ + if self.tokentype_embeddings is not None: + raise Exception('tokentype embeddings is already initialized') + if torch.distributed.get_rank() == 0: + print('adding embedding for {} tokentypes'.format(num_tokentypes), + flush=True) + self.num_tokentypes = num_tokentypes + self.tokentype_embeddings = torch.nn.Embedding(num_tokentypes, + self.hidden_size) + # Initialize the token-type embeddings. + args = get_args() + self.init_method(self.tokentype_embeddings.weight) + + def forward(self, input_ids, position_ids, tokentype_ids=None): + # Embeddings. + if self.embedding_weights_in_fp32: + self.word_embeddings = self.word_embeddings.to(torch.float32) + words_embeddings = self.word_embeddings(input_ids) + if self.embedding_weights_in_fp32: + words_embeddings = words_embeddings.to(self.params_dtype) + self.word_embeddings = self.word_embeddings.to(self.params_dtype) + if self.add_position_embedding: + position_embeddings = self.position_embeddings(position_ids) + embeddings = words_embeddings + position_embeddings + else: + embeddings = words_embeddings + + if tokentype_ids is not None: + assert self.tokentype_embeddings is not None + embeddings = embeddings + self.tokentype_embeddings(tokentype_ids) + else: + assert self.tokentype_embeddings is None + + # Data format change to avoid explicit tranposes : [b s h] --> [s b h]. + embeddings = embeddings.transpose(0, 1).contiguous() + + # If the input flag for fp32 residual connection is set, convert for float. + if self.fp32_residual_connection: + embeddings = embeddings.float() + + # Dropout. + if self.sequence_parallel: + # already partition sequence, do not need scatter_to_sequence_parallel_region ? + embeddings = tensor_parallel.scatter_to_sequence_parallel_region(embeddings) + with tensor_parallel.get_cuda_rng_tracker().fork(): + embeddings = self.embedding_dropout(embeddings) + else: + embeddings = self.embedding_dropout(embeddings) + + return embeddings + + def state_dict_for_save_checkpoint(self, prefix='', keep_vars=False): + """For easy load.""" + + state_dict_ = {} + state_dict_[self._word_embeddings_key] \ + = self.word_embeddings.state_dict(prefix=prefix, + keep_vars=keep_vars) + if self.add_position_embedding: + state_dict_[self._position_embeddings_key] \ + = self.position_embeddings.state_dict(prefix=prefix, + keep_vars=keep_vars) + if self.num_tokentypes > 0: + state_dict_[self._tokentype_embeddings_key] \ + = self.tokentype_embeddings.state_dict(prefix=prefix, + keep_vars=keep_vars) + + return state_dict_ + + def load_state_dict(self, state_dict, strict=True): + """Customized load.""" + + # Word embedding. + if self._word_embeddings_key in state_dict: + state_dict_ = state_dict[self._word_embeddings_key] + else: + # for backward compatibility. + state_dict_ = {} + for key in state_dict.keys(): + if 'word_embeddings' in key: + state_dict_[key.split('word_embeddings.')[1]] \ + = state_dict[key] + self.word_embeddings.load_state_dict(state_dict_, strict=strict) + + # Position embedding. + if self.add_position_embedding: + if self._position_embeddings_key in state_dict: + state_dict_ = state_dict[self._position_embeddings_key] + else: + # for backward compatibility. + state_dict_ = {} + for key in state_dict.keys(): + if 'position_embeddings' in key: + state_dict_[key.split('position_embeddings.')[1]] \ + = state_dict[key] + self.position_embeddings.load_state_dict(state_dict_, strict=strict) + + # Tokentype embedding. + if self.num_tokentypes > 0: + state_dict_ = {} + if self._tokentype_embeddings_key in state_dict: + state_dict_ = state_dict[self._tokentype_embeddings_key] + else: + # for backward compatibility. + for key in state_dict.keys(): + if 'tokentype_embeddings' in key: + state_dict_[key.split('tokentype_embeddings.')[1]] \ + = state_dict[key] + if len(state_dict_.keys()) > 0: + self.tokentype_embeddings.load_state_dict(state_dict_, + strict=strict) + else: + print('***WARNING*** expected tokentype embeddings in the ' + 'checkpoint but could not find it', flush=True) + + +class EmbeddingPipe(Embedding): + + def forward(self, inputs, **kwargs): + if not hasattr(self, '_args'): + self._args = get_args() + + input_ids = inputs[0] + position_ids = inputs[1] + if hasattr(self._args, 'attn_mask'): + attention_mask = None + else: + attention_mask = inputs[2] + + if len(inputs) == 4: + tokentype_ids = inputs[3] + else: + tokentype_ids = None + + embeddings = super().forward(input_ids, position_ids, tokentype_ids=tokentype_ids) + + # If cmd args has attn_mask, we don't forward it as an activation. + if hasattr(self._args, 'attn_mask'): + return embeddings + else: + assert False + return embeddings, attention_mask + + + @property + def word_embeddings_weight(self): + """Easy accessory for the DeepSpeed pipeline engine to tie embeddings across stages.""" + return self.word_embeddings.weight + + +class TransformerLanguageModel(MegatronModule): + """Transformer language model. + + Arguments: + transformer_hparams: transformer hyperparameters + vocab_size: vocabulary size + max_sequence_length: maximum size of sequence. This + is used for positional embedding + embedding_dropout_prob: dropout probability for embeddings + num_tokentypes: size of the token-type embeddings. 0 value + will ignore this embedding + """ + + def __init__(self, + config, + encoder_attn_mask_type, + num_tokentypes=0, + add_encoder=True, + add_decoder=False, + decoder_attn_mask_type=AttnMaskType.causal, + add_pooler=False, + pre_process=True, + post_process=True, + num_experts=[1]): + args = get_args() + # TODO: passing share_embeddings_and_output_weights=False will not work correctly for T5 and embeddings will not be synced. Fix later for T5. + if args.untie_embeddings_and_output_weights: assert not add_decoder + super(TransformerLanguageModel, self).__init__(share_embeddings_and_output_weights=not args.untie_embeddings_and_output_weights) + + self.pre_process = pre_process + self.post_process = post_process + self.hidden_size = config.hidden_size + self.num_tokentypes = num_tokentypes + self.init_method = config.init_method + self.add_encoder = add_encoder + self.encoder_attn_mask_type = encoder_attn_mask_type + self.add_decoder = add_decoder + self.decoder_attn_mask_type = decoder_attn_mask_type + self.add_pooler = add_pooler + self.encoder_hidden_state = None + self.add_retriever = args.retro_add_retriever + self.untie_embeddings_and_output_weights = args.untie_embeddings_and_output_weights + self.num_experts = num_experts + + # Embeddings. + if self.pre_process: + self.embedding = Embedding(self.hidden_size, + args.padded_vocab_size, + args.max_position_embeddings, + args.hidden_dropout, + config, + args.add_position_embedding, + self.num_tokentypes, + args.embedding_weights_in_fp32) + self._embedding_key = 'embedding' + + # Rotary positional embeddings + self.use_rotary_position_embeddings = \ + args.use_rotary_position_embeddings + if args.use_rotary_position_embeddings: + self.seq_length = args.seq_length + rotary_dim = args.hidden_size // args.num_attention_heads \ + if args.kv_channels is None else args.kv_channels + + if args.rotary_percent < 1.0: + rotary_dim = int(rotary_dim * args.rotary_percent) + + # partial rotary embeddings, which is better than full rotary + # Wang and Komatsuzaki et al + # https://github.com/kingoflolz/mesh-transformer-jax/ + self.rotary_pos_emb = RotaryEmbedding(rotary_dim) + + # Encoder (usually set to True, False if part of an encoder-decoder + # architecture and in encoder-only stage). + if self.add_encoder: + self.encoder = ParallelTransformer( + config, + model_type=args.model_type if not args.retro_add_retriever \ + else ModelType.retro_decoder, + self_attn_mask_type=self.encoder_attn_mask_type, + pre_process=self.pre_process, + post_process=self.post_process, + num_experts=self.num_experts + ) + self._encoder_key = 'encoder' + else: + self.encoder = None + + # Decoder (usually set to False, True if part of an encoder-decoder + # architecture and in decoder-only stage). + if self.add_decoder: + self.decoder = ParallelTransformer( + config, + model_type=args.model_type, + layer_type=LayerType.decoder, + self_attn_mask_type=self.decoder_attn_mask_type, + pre_process=self.pre_process, + post_process=self.post_process, + num_experts=self.num_experts) + self._decoder_key = 'decoder' + else: + self.decoder = None + + if self.post_process: + # Pooler. + if self.add_pooler: + self.pooler = Pooler(self.hidden_size, self.init_method) + self._pooler_key = 'pooler' + + if self.untie_embeddings_and_output_weights: + self.output_layer = tensor_parallel.ColumnParallelLinear( + args.hidden_size, + args.padded_vocab_size, + config=config, + init_method=self.init_method, + bias=False) # Setting bias to False always to keep it consistent with embedding tying that also does not have a bias. + self._output_layer_key = 'output_layer' + + def set_input_tensor(self, input_tensor): + """ See megatron.model.transformer.set_input_tensor()""" + + # This is usually handled in schedules.py but some inference code still + # gives us non-lists or None + if not isinstance(input_tensor, list): + input_tensor = [input_tensor] + + if self.add_encoder and self.add_decoder: + assert len(input_tensor) == 1, \ + 'input_tensor should only be length 1 for stage with both encoder and decoder' + self.encoder.set_input_tensor(input_tensor[0]) + elif self.add_encoder: + assert len(input_tensor) == 1, \ + 'input_tensor should only be length 1 for stage with only encoder' + self.encoder.set_input_tensor(input_tensor[0]) + elif self.add_decoder: + if len(input_tensor) == 2: + self.decoder.set_input_tensor(input_tensor[0]) + self.encoder_hidden_state = input_tensor[1] + elif len(input_tensor) == 1: + self.decoder.set_input_tensor(None) + self.encoder_hidden_state = input_tensor[0] + else: + raise Exception('input_tensor must have either length 1 or 2') + else: + raise Exception('Stage must have at least either encoder or decoder') + + def forward(self, enc_input_ids, enc_position_ids, enc_attn_mask, + dec_input_ids=None, dec_position_ids=None, dec_attn_mask=None, + retriever_input_ids=None, + retriever_position_ids=None, + retriever_attn_mask=None, + enc_dec_attn_mask=None, tokentype_ids=None, + inference_params=None, + pooling_sequence_index=0, + enc_hidden_states=None, output_enc_hidden=False): + args = get_args() + # Encoder embedding. + if self.pre_process: + encoder_input = self.embedding(enc_input_ids, enc_position_ids, + tokentype_ids=tokentype_ids) + else: + encoder_input = None + + # Retriever embedding. + if self.add_retriever and self.pre_process: + retriever_input = self.embedding(retriever_input_ids, + retriever_position_ids, + tokentype_ids=tokentype_ids) + else: + retriever_input = None + + # Rotary positional embeddings + rotary_pos_emb = None + if self.use_rotary_position_embeddings: + if inference_params is not None: + rotary_pos_emb = \ + self.rotary_pos_emb(inference_params.max_sequence_len) + else: + if args.curriculum_learning_legacy or args.data_efficiency_curriculum_learning: + rotary_pos_emb = self.rotary_pos_emb(args.curriculum_seqlen) + else: + rotary_pos_emb = self.rotary_pos_emb(self.seq_length) + + # Run encoder. + if enc_hidden_states is None: + if self.encoder is not None: + encoder_output, *encoder_moe_losses = self.encoder( + encoder_input, + enc_attn_mask, + retriever_input=retriever_input, + retriever_attn_mask=retriever_attn_mask, + inference_params=inference_params, + rotary_pos_emb=rotary_pos_emb) + else: + encoder_output = self.encoder_hidden_state + else: + encoder_output, encoder_moe_losses = enc_hidden_states.to(encoder_input.dtype), [] + + if self.post_process: + if self.add_pooler: + pooled_output = self.pooler(encoder_output, + pooling_sequence_index) + + # output_enc_hidden refers to when we just need the encoder's + # output. For example, it is helpful to compute + # similarity between two sequences by average pooling + if not self.add_decoder or output_enc_hidden: + if self.add_pooler and self.post_process: + return encoder_output, pooled_output, encoder_moe_losses + else: + return encoder_output, encoder_moe_losses + + # Decoder embedding. + if self.pre_process: + decoder_input = self.embedding(dec_input_ids, + dec_position_ids) + else: + decoder_input = None + + # Run decoder. + decoder_output, *decoder_moe_losses = self.decoder( + decoder_input, + dec_attn_mask, + encoder_output=encoder_output, + enc_dec_attn_mask=enc_dec_attn_mask, + inference_params=inference_params, + rotary_pos_emb=rotary_pos_emb) + + if self.add_pooler and self.post_process: + return decoder_output, encoder_output, pooled_output, decoder_moe_losses, encoder_moe_losses + else: + return decoder_output, encoder_output, decoder_moe_losses, encoder_moe_losses + + def state_dict_for_save_checkpoint(self, prefix='', keep_vars=False): + """For easy load.""" + args = get_args() + state_dict_ = {} + moe_state_dict = {} + if self.pre_process: + state_dict_[self._embedding_key] \ + = self.embedding.state_dict_for_save_checkpoint(prefix=prefix, + keep_vars=keep_vars) + if self.add_encoder: + encoder_state_dict = self.encoder.state_dict_for_save_checkpoint( + prefix=prefix, keep_vars=keep_vars) + if args.random_ltd: + # When using random-LTD, it is required to call remove_random_ltd_state_dict + # during model checkpoint saving to transfer the random-LTD-wrapped + # layers back to original layers. This will help to remove the dependency + # to random-LTD inside the checkpoint, so that during evaluation or + # finetuning of the checkpoint there is no need to depend on random-LTD + # again. + from deepspeed.runtime.data_pipeline.data_routing.helper import remove_random_ltd_state_dict + encoder_state_dict = remove_random_ltd_state_dict(encoder_state_dict) + # MoE states need to be handled separately by DeepSpeed engine, thus + # moving them to the top level dictionary + # If components other than encoder may contain MoE states, need to add + # the same logic + for key in list(encoder_state_dict.keys()): + if 'expert' in key and 'moe.gate.wg.weight' not in key: + moe_state_dict[self._encoder_key+key] = encoder_state_dict.pop(key) + state_dict_[self._encoder_key] = encoder_state_dict + + if self.post_process: + if self.add_pooler: + state_dict_[self._pooler_key] \ + = self.pooler.state_dict_for_save_checkpoint(prefix=prefix, + keep_vars=keep_vars) + if self.untie_embeddings_and_output_weights: + state_dict_[self._output_layer_key] \ + = self.output_layer.state_dict(prefix=prefix, keep_vars=keep_vars) + + if self.add_decoder: + state_dict_[self._decoder_key] \ + = self.decoder.state_dict_for_save_checkpoint(prefix=prefix, + keep_vars=keep_vars) + + state_dict_["moe_state_dict"] = moe_state_dict + return state_dict_ + + def load_state_dict(self, state_dict, strict=True): + """Customized load.""" + + # Embedding. + if self.pre_process: + if self._embedding_key in state_dict: + state_dict_ = state_dict[self._embedding_key] + else: + # for backward compatibility. + state_dict_ = {} + for key in state_dict.keys(): + if '_embeddings' in key: + state_dict_[key] = state_dict[key] + self.embedding.load_state_dict(state_dict_, strict=strict) + + # Encoder. + if self.add_encoder: + if self._encoder_key in state_dict: + state_dict_ = state_dict[self._encoder_key] + # For backward compatibility. + elif 'transformer' in state_dict: + state_dict_ = state_dict['transformer'] + else: + # For backward compatibility. + state_dict_ = {} + for key in state_dict.keys(): + if 'transformer.' in key: + state_dict_[key.split('transformer.')[1]] = state_dict[key] + + # For backward compatibility. + # Somehow this backward compatibility could be wrong: sometimes + # '.attention.' is the actual key used so should not be replaced. Thus + # added another logic to only replace if the key does not match + state_dict_self_attention = {} + encoder_state_dict_keys = list(self.encoder.state_dict().keys()) + for key in state_dict_.keys(): + if '.attention.' in key and key not in encoder_state_dict_keys: + state_dict_self_attention[key.replace(".attention.", + ".self_attention.")] = state_dict_[key] + else: + state_dict_self_attention[key] = state_dict_[key] + state_dict_ = state_dict_self_attention + + # Gather encoder MoE states + if "moe_state_dict" in state_dict: + for key in list(state_dict["moe_state_dict"].keys()): + if self._encoder_key in key: + key_list = key.split('.') + while key_list[0] != 'encoder': + key_list.pop(0) + key_list.pop(0) + actual_key = '.'.join(key_list) + state_dict_[actual_key] = state_dict["moe_state_dict"].pop(key) + if len(state_dict["moe_state_dict"]) == 0: + del state_dict["moe_state_dict"] + self.encoder.load_state_dict(state_dict_, strict=strict) + + # Pooler. + if self.post_process: + if self.add_pooler: + assert 'pooler' in state_dict, \ + 'could not find data for pooler in the checkpoint' + self.pooler.load_state_dict(state_dict[self._pooler_key], + strict=strict) + if self.untie_embeddings_and_output_weights: + assert 'output_layer' in state_dict, \ + 'could not find data for output_layer in the checkpoint' + self.output_layer.load_state_dict(state_dict[self._output_layer_key], + strict=strict) + # Decoder. + if self.add_decoder: + assert 'decoder' in state_dict, \ + 'could not find data for pooler in the checkpoint' + self.decoder.load_state_dict(state_dict[self._decoder_key], + strict=strict) diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/module.py b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/module.py new file mode 100644 index 0000000000000000000000000000000000000000..93d236ba4352d3987d8128e309b64f3914cdf692 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/module.py @@ -0,0 +1,206 @@ +# Copyright (C) 2024 Habana Labs, Ltd. an Intel Company. +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. + +"""Megatron Module""" + +import torch +from torch.autograd import Variable +from torch.nn.parameter import Parameter +from deepspeed.accelerator import get_accelerator +from megatron import get_args +from megatron.core import mpu, tensor_parallel + + +if get_accelerator().device_name() == "hpu": + # revert this once [SW-160732] is fixed + _FLOAT_TYPES = (torch.FloatTensor, ) + _HALF_TYPES = (torch.HalfTensor, ) + _BF16_TYPES = (torch.BFloat16Tensor, ) +else: + _FLOAT_TYPES = (torch.FloatTensor, get_accelerator().FloatTensor) + _HALF_TYPES = (torch.HalfTensor, get_accelerator().HalfTensor) + _BF16_TYPES = (torch.BFloat16Tensor, get_accelerator().BFloat16Tensor) + + + +def param_is_not_shared(param): + return not hasattr(param, 'shared') or not param.shared + + + +class MegatronModule(torch.nn.Module): + """Megatron specific extensions of torch Module with support + for pipelining.""" + + def __init__(self, config=None, share_embeddings_and_output_weights=True): + super(MegatronModule, self).__init__() + self.config = config + self.share_embeddings_and_output_weights = share_embeddings_and_output_weights + + + def state_dict_for_save_checkpoint(self, prefix='', keep_vars=False): + """Use this function to override the state dict for + saving checkpoints.""" + return self.state_dict(prefix=prefix, keep_vars=keep_vars) + + + def shared_embedding_or_output_weight(self): + if self.pre_process: + return self.language_model.embedding.word_embeddings.weight + else: + if not self.share_embeddings_and_output_weights: + raise Exception('shared_embedding_or_output_weight() called for last ' + 'stage, but share_embeddings_and_output_weights is false') + return self.word_embeddings.weight + + + def initialize_word_embeddings(self): + args = get_args() + if not self.share_embeddings_and_output_weights: + raise Exception('initialize_word_embeddings() was called but ' + 'share_embeddings_and_output_weights is false') + + # This function just initializes the word embeddings in the final stage + # when we are using pipeline parallelism. Nothing to do if we aren't + # using pipeline parallelism. + if args.pipeline_model_parallel_size == 1: + return + + # Parameters are shared between the word embeddings layers, and the + # heads at the end of the model. In a pipelined setup with more than + # one stage, the initial embedding layer and the head are on different + # workers, so we do the following: + # 1. Create a second copy of word_embeddings on the last stage, with + # initial parameters of 0.0. + # 2. Do an all-reduce between the first and last stage to ensure that + # the two copies of word_embeddings start off with the same + # parameter values. + # 3. In the training loop, before an all-reduce between the grads of + # the two word_embeddings layers to ensure that every applied weight + # update is the same on both stages. + if mpu.is_pipeline_last_stage() and not self.pre_process: + assert not mpu.is_pipeline_first_stage() + self._word_embeddings_for_head_key = 'word_embeddings_for_head' + # set word_embeddings weights to 0 here, then copy first + # stage's weights using all_reduce below. + self.word_embeddings = tensor_parallel.VocabParallelEmbedding( + args.padded_vocab_size, self.config.hidden_size, + config=self.config, init_method=self.config.init_method) + self.word_embeddings.weight.data.fill_(0) + self.word_embeddings.weight.shared = True + + # Zero out initial weights for decoder embedding. + # NOTE: We don't currently support T5 with the interleaved schedule. + if not mpu.is_pipeline_first_stage(ignore_virtual=True) and \ + self.pre_process: + self.language_model.embedding.zero_parameters() + + if not torch.distributed.is_initialized(): + if not getattr(MegatronModule, "embedding_warning_printed", False): + print("WARNING! Distributed processes aren't initialized, so " + "word embeddings in the last layer are not initialized. " + "If you are just manipulating a model this is fine, but " + "this needs to be handled manually. If you are training " + "something is definitely wrong.") + MegatronModule.embedding_warning_printed = True + return + + # Ensure that first and last stages have the same initial parameter + # values. + if mpu.is_rank_in_embedding_group(): + torch.distributed.all_reduce(self.shared_embedding_or_output_weight().data, + group=mpu.get_embedding_group()) + + # Ensure that encoder(first stage) and decoder(split stage) position + # embeddings have the same initial parameter values + # NOTE: We don't currently support T5 with the interleaved schedule. + if mpu.is_rank_in_position_embedding_group() and \ + args.pipeline_model_parallel_split_rank is not None: + # TODO: Support tokentype embedding. + self.language_model.embedding.cuda() + position_embeddings = self.language_model.embedding.position_embeddings + torch.distributed.all_reduce(position_embeddings.weight.data, + group=mpu.get_position_embedding_group()) + + def universal_checkpoint_info(self): + return {} + +def conversion_helper(val, conversion): + """Apply conversion to val. Recursively apply conversion if `val` + #is a nested tuple/list structure.""" + if not isinstance(val, (tuple, list)): + return conversion(val) + rtn = [conversion_helper(v, conversion) for v in val] + if isinstance(val, tuple): + rtn = tuple(rtn) + return rtn + + +def fp32_to_float16(val, float16_convertor): + """Convert fp32 `val` to fp16/bf16""" + def half_conversion(val): + val_typecheck = val + if isinstance(val_typecheck, (Parameter, Variable)): + val_typecheck = val.data + if isinstance(val_typecheck, _FLOAT_TYPES): + val = float16_convertor(val) + return val + return conversion_helper(val, half_conversion) + + +def float16_to_fp32(val): + """Convert fp16/bf16 `val` to fp32""" + def float_conversion(val): + val_typecheck = val + if isinstance(val_typecheck, (Parameter, Variable)): + val_typecheck = val.data + if isinstance(val_typecheck, (_BF16_TYPES, _HALF_TYPES)): + val = val.float() + return val + return conversion_helper(val, float_conversion) + + + +class Float16Module(MegatronModule): + + def __init__(self, module, args): + super(Float16Module, self).__init__() + + if args.fp16: + self.add_module('module', module.half()) + def float16_convertor(val): + return val.half() + elif args.bf16: + self.add_module('module', module.bfloat16()) + def float16_convertor(val): + return val.bfloat16() + else: + raise Exception('should not be here') + + self.float16_convertor = float16_convertor + + + def set_input_tensor(self, input_tensor): + return self.module.set_input_tensor(input_tensor) + + + def forward(self, *inputs, **kwargs): + if mpu.is_pipeline_first_stage(): + inputs = fp32_to_float16(inputs, self.float16_convertor) + outputs = self.module(*inputs, **kwargs) + if mpu.is_pipeline_last_stage(): + outputs = float16_to_fp32(outputs) + return outputs + + + def state_dict(self, prefix='', keep_vars=False): + return self.module.state_dict(prefix=prefix, keep_vars=keep_vars) + + + def state_dict_for_save_checkpoint(self, prefix='', keep_vars=False): + return self.module.state_dict_for_save_checkpoint(prefix=prefix, + keep_vars=keep_vars) + + + def load_state_dict(self, state_dict, strict=True): + self.module.load_state_dict(state_dict, strict=strict) diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/multiple_choice.py b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/multiple_choice.py new file mode 100644 index 0000000000000000000000000000000000000000..13e1e34a9ab9aaaa5220b3bf26ca3477aaeef895 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/multiple_choice.py @@ -0,0 +1,113 @@ +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. + +"""Multiple choice model.""" + +import torch + +from megatron import get_args, print_rank_last +from megatron.model.enums import AttnMaskType +from megatron.model.bert_model import bert_extended_attention_mask, bert_position_ids +from megatron.model.language_model import get_language_model +from megatron.model.utils import get_linear_layer +from megatron.model.utils import init_method_normal +from megatron.model.utils import scaled_init_method_normal +from .module import MegatronModule + + +class MultipleChoice(MegatronModule): + + def __init__(self, + config, + num_tokentypes=2, + pre_process=True, + post_process=True): + super(MultipleChoice, self).__init__(share_embeddings_and_output_weights=False) + args = get_args() + + self.pre_process = pre_process + self.post_process = post_process + + self.language_model, self._language_model_key = get_language_model( + config=config, + num_tokentypes=num_tokentypes, + add_pooler=True, + encoder_attn_mask_type=AttnMaskType.padding, + pre_process=self.pre_process, + post_process=self.post_process) + + # Multi-choice head. + if self.post_process: + self.multichoice_dropout = torch.nn.Dropout(args.hidden_dropout) + self.multichoice_head = get_linear_layer(args.hidden_size, 1, + init_method, + gather_params_on_init=args.zero_stage == 3) + self._multichoice_head_key = 'multichoice_head' + + def set_input_tensor(self, input_tensor): + """See megatron.model.transformer.set_input_tensor()""" + self.language_model.set_input_tensor(input_tensor) + + def forward(self, model_input, attention_mask, tokentype_ids=None): + + # [batch, choices, sequence] --> [batch * choices, sequence] --> + # transformer --> [batch, choices] --> softmax + + # Ensure the shape is [batch-size, choices, sequence] + assert len(attention_mask.shape) == 3 + num_choices = attention_mask.shape[1] + + # Reshape and treat choice dimension the same as batch. + attention_mask = attention_mask.view(-1, attention_mask.size(-1)) + extended_attention_mask = bert_extended_attention_mask(attention_mask) + + input_ids = model_input + # Do the same as attention_mask for input_ids, tokentype_ids + assert len(input_ids.shape) == 3 + assert len(tokentype_ids.shape) == 3 + input_ids = input_ids.view(-1, input_ids.size(-1)) + tokentype_ids = tokentype_ids.view(-1, tokentype_ids.size(-1)) + position_ids = bert_position_ids(input_ids) + + lm_output = self.language_model( + input_ids, + position_ids, + extended_attention_mask, + tokentype_ids=tokentype_ids + ) + if self.post_process: + _, pooled_output = lm_output[0], lm_output[1] + multichoice_output = self.multichoice_dropout(pooled_output) + multichoice_logits = self.multichoice_head(multichoice_output) + + # Reshape back to separate choices. + multichoice_logits = multichoice_logits.view(-1, num_choices) + + return multichoice_logits + return lm_output + + def state_dict_for_save_checkpoint(self, prefix='', keep_vars=False): + """For easy load when model is combined with other heads, + add an extra key.""" + + state_dict_ = {} + state_dict_[self._language_model_key] \ + = self.language_model.state_dict_for_save_checkpoint(prefix=prefix, + keep_vars=keep_vars) + if self.post_process: + state_dict_[self._multichoice_head_key] \ + = self.multichoice_head.state_dict(prefix=prefix, keep_vars=keep_vars) + return state_dict_ + + def load_state_dict(self, state_dict, strict=True): + """Customized load.""" + + self.language_model.load_state_dict( + state_dict[self._language_model_key], strict=strict) + if self.post_process: + if self._multichoice_head_key in state_dict: + self.multichoice_head.load_state_dict( + state_dict[self._multichoice_head_key], strict=strict) + else: + print_rank_last('***WARNING*** could not find {} in the checkpoint, ' + 'initializing to random'.format( + self._multichoice_head_key)) diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/rmsnorm.py b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/rmsnorm.py new file mode 100644 index 0000000000000000000000000000000000000000..c58ba26d0e8e7ce4ea4c51b033b89a37d3cc3716 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/rmsnorm.py @@ -0,0 +1,49 @@ +# Copyright (C) 2024 Habana Labs, Ltd. an Intel Company. +# coding=utf-8 +# 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. + +from deepspeed.accelerator import get_accelerator +from megatron import get_args + +import torch +from torch.nn import init +from torch.nn.parameter import Parameter + +try: + from habana_frameworks.torch.hpex.normalization import FusedRMSNorm +except: + FusedRMSNorm = None + + +class RMSNorm(torch.nn.Module): + def __init__(self, dim, eps=1e-5, sequence_parallel=False): + super().__init__() + self.epsilon = eps + self.weight = Parameter(torch.empty(dim, + device=get_accelerator().current_device_name(), + dtype=get_args().params_dtype)) + init.ones_(self.weight) + self.use_fused_rmsnorm = get_args().use_fused_rmsnorm + + if sequence_parallel: + setattr(self.weight, 'sequence_parallel', sequence_parallel) + + def forward(self, x): + if self.use_fused_rmsnorm and x.device.type == "hpu": + assert FusedRMSNorm is not None, "failed to import FusedRMSNorm" + return FusedRMSNorm.apply(x, self.weight, self.epsilon) + dtype = x.dtype + x = x.float() + norm = torch.mean(x**2, -1, keepdim=True) + norm = x.mul(norm.add_(self.epsilon).rsqrt_()) + return self.weight * norm.to(dtype) diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/transformer.py b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..ab526d2d0c4c7e20d1fad0bc921f9399bee02b1c --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/transformer.py @@ -0,0 +1,2102 @@ +# Copyright (C) 2024 Habana Labs, Ltd. an Intel Company. +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. + +"""Transformer.""" +from contextlib import nullcontext +import math +import numpy as np +import torch +import torch.nn.functional as F +from typing import Optional + +from megatron import get_timers, get_args, get_retro_args, core, get_num_microbatches +from .module import MegatronModule +from .rmsnorm import RMSNorm +from megatron.core import parallel_state, tensor_parallel, mpu +from megatron.core.enums import ModelType +from megatron.model import LayerNorm +from megatron.model.enums import AttnMaskType, LayerType, AttnType +from megatron.model.fused_softmax import FusedScaleMaskSoftmax +from megatron.model.fused_bias_gelu import bias_gelu_impl +from megatron.model.rotary_pos_embedding import apply_rotary_pos_emb +from megatron.model.utils import attention_mask_func, openai_gelu, erf_gelu +import deepspeed +from deepspeed.moe.layer import MoE +from deepspeed.accelerator import get_accelerator + +try: + from deepspeed.sequence.layer import DistributedAttention + dist_attn_supported = True +except ImportError: + dist_attn_supported = False + +try: + from einops import rearrange +except ImportError: + rearrange = None + +try: + # FlashAttention (1.x) + from flash_attn.flash_attn_interface import flash_attn_unpadded_func + from flash_attn.flash_attn_triton import flash_attn_func +except ImportError: + flash_attn_unpadded_func = None + flash_attn_func = None + +try: + # FlashAttention-2 + from flash_attn.flash_attn_interface import flash_attn_varlen_func +except ImportError: + flash_attn_varlen_func = None + +FlashAttentionBuilder = get_accelerator().get_op_builder("FlashAttentionBuilder") +flash_attn_builder = None +try: + flash_attn_builder = FlashAttentionBuilder().load() +except (TypeError, ValueError): + flash_attn_builder = None + +try: + from apex.normalization import MixedFusedRMSNorm +except ImportError: + MixedFusedRMSNorm = RMSNorm + +try: + import habana_frameworks.torch.hpu as hthpu + from habana_frameworks.torch.hpex.kernels import FusedSDPA +except ImportError: + hthpu = None + FusedSDPA = None + + +""" We use the following notation throughout this file: + h: hidden size + n: number of attention heads + p: number of model parallel partitions + np: n/p + hp: h/p + hn: h/n + b: batch size + s: sequence length + l: number of layers + Transformer takes input of size [s, b, h] and returns a + tensor of the same size. We use the following arguments: + hyperparameters: transformer hyperparameters +""" + +class DropPath(MegatronModule): + """Drop paths (Stochastic Depth) per sample + (when applied in main path of residual blocks). + """ + + def __init__(self, drop_prob=0.): + super(DropPath, self).__init__() + self.drop_prob = drop_prob + + def forward(self, hidden_state): + if self.drop_prob == 0. or not self.training: + return hidden_state + keep_prob = 1 - self.drop_prob + # work with diff dim tensors, not just 2D ConvNets + # hidden_state: [s, b, h] + shape = (1,) + (hidden_state.shape[1],) + (1,) * (hidden_state.ndim - 2) + random_tensor = keep_prob + \ + torch.rand(shape, dtype=hidden_state.dtype, device=hidden_state.device) + random_tensor.floor_() # binarize + output = hidden_state.div(keep_prob) * random_tensor + return output + +class ParallelMLP(MegatronModule): + """MLP. + + MLP will take the input with h hidden state, project it to 4*h + hidden dimension, perform nonlinear transformation, and project the + state back into h hidden dimension. + """ + + def __init__(self, config, moe=False, enable_expert_tensor_parallelism=False): + super(ParallelMLP, self).__init__() + args = get_args() + + self.add_bias = config.add_bias_linear + + ffn_hidden_size = config.ffn_hidden_size + if config.gated_linear_unit: + ffn_hidden_size *= 2 + + # Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf + self.dense_h_to_4h = tensor_parallel.ColumnParallelLinear( + config.hidden_size, + ffn_hidden_size, + config=config, + init_method=config.init_method, + bias=self.add_bias, + gather_output=False, + skip_bias_add=True, + moe=moe, + enable_expert_tensor_parallelism=enable_expert_tensor_parallelism + ) + + self.bias_gelu_fusion = False + self.activation_func = None + self.swiglu = args.swiglu + + if args.openai_gelu: + self.activation_func = openai_gelu + elif args.onnx_safe: + self.activation_func = erf_gelu + elif args.swiglu: + def swiglu(x): + x = torch.chunk(x, 2, dim=-1) + return F.silu(x[0]) * x[1] + self.activation_func = swiglu + elif args.squared_relu: + def squared_relu(x): + return torch.pow(F.relu(x), 2) + self.activation_func = squared_relu + else: + self.bias_gelu_fusion = args.bias_gelu_fusion + self.activation_func = F.gelu + + # Project back to h. + self.dense_4h_to_h = tensor_parallel.RowParallelLinear( + config.ffn_hidden_size, + config.hidden_size, + config=config, + init_method=config.output_layer_init_method, + bias=self.add_bias, + input_is_parallel=True, + moe=moe, + enable_expert_tensor_parallelism=enable_expert_tensor_parallelism + ) + + def forward(self, hidden_states): + + # [s, b, 4hp] + intermediate_parallel, bias_parallel = self.dense_h_to_4h(hidden_states) + + if self.bias_gelu_fusion: + assert self.add_bias is True + # DeepSpeed FLOPS profiler temporarily substitues functions like F.gelu to calculate the throughput + assert hasattr(self, "__flops__") or self.activation_func == F.gelu + intermediate_parallel = bias_gelu_impl(intermediate_parallel, bias_parallel) + else: + if bias_parallel is not None: + intermediate_parallel = intermediate_parallel + bias_parallel + intermediate_parallel = self.activation_func(intermediate_parallel) + + # [s, b, h] + output, output_bias = self.dense_4h_to_h(intermediate_parallel) + return output, output_bias + +class SwitchMLP(MegatronModule): + """ + Routes input to one of N MLP "experts" + """ + def __init__(self, config): + super(SwitchMLP, self).__init__() + args = get_args() + self.router = torch.nn.Linear(config.hidden_size, args.num_experts_switch) + self.experts = torch.nn.ModuleList() + for i in range(args.num_experts_switch): + self.experts.append(ParallelMLP(config)) + + def forward(self, hidden_states): + # hidden_states: [s, b, h] + s = hidden_states.size(0) + b = hidden_states.size(1) + h = hidden_states.size(2) + route = self.router(hidden_states) + route = torch.nn.functional.softmax(route, dim=2) + max_prob, max_ind = torch.max(route, dim=2) + max_prob = torch.unsqueeze(max_prob, 2) # [s b 1] + + # TODO (rprenger) TODO this could be made easier to read + # Converting [s, b, h] to [s*b, h]. + # Each vector could be routed differently + hidden_states = hidden_states.view(-1, hidden_states.size(2)) # [s*b h] + max_prob = max_prob.view(-1, max_prob.size(2)) # [s*b 1] + max_ind = max_ind.view(-1) # [s*b] + + output_total = torch.empty_like(hidden_states) + output_bias_total = torch.empty_like(hidden_states) + #TODO (rprenger) This does each expert in serial, but it could be parallelized + + for expert_num, expert in enumerate(self.experts): + local_indices = (max_ind == expert_num).nonzero() + hidden = hidden_states[local_indices,:] + output, output_bias = expert(hidden) + output_bias = output_bias.expand_as(output) + output_total[local_indices,:] = output + output_bias_total[local_indices,:] = output_bias + + output_total = output_total*max_prob + output_bias_total = output_bias_total*max_prob + output_total = output_total.view(s, b, h) + output_bias_total = output_bias_total.view(s, b, h) + + return output_total, output_bias_total + + +class CoreAttention(MegatronModule): + + def __init__(self, layer_number, config, + attn_mask_type=AttnMaskType.padding): + super(CoreAttention, self).__init__() + self.fp16 = config.fp16 + self.bf16 = config.bf16 + + self.apply_query_key_layer_scaling = config.apply_query_key_layer_scaling + self.attention_softmax_in_fp32 = config.attention_softmax_in_fp32 + if self.apply_query_key_layer_scaling: + self.attention_softmax_in_fp32 = True + self.layer_number = max(1, layer_number+1) + self.attn_mask_type = attn_mask_type + self.sequence_parallel = config.sequence_parallel + + projection_size = config.kv_channels * config.num_attention_heads + + # Per attention head and per partition values. + seq_parallel_world_size = 1 + if parallel_state.sequence_parallel_is_initialized(): + seq_parallel_world_size = parallel_state.get_sequence_parallel_world_size() + world_size = seq_parallel_world_size if seq_parallel_world_size > 1 else parallel_state.get_tensor_model_parallel_world_size() + + self.hidden_size_per_partition = core.utils.divide(projection_size, + world_size) + self.hidden_size_per_attention_head = core.utils.divide( + projection_size, config.num_attention_heads) + self.num_attention_heads_per_partition = core.utils.divide( + config.num_attention_heads, world_size) + + coeff = None + self.norm_factor = math.sqrt(self.hidden_size_per_attention_head) + if self.apply_query_key_layer_scaling: + coeff = self.layer_number + self.norm_factor *= coeff + + self.scale_mask_softmax = FusedScaleMaskSoftmax( + self.fp16, self.bf16, + self.attn_mask_type, + config.masked_softmax_fusion, + attention_mask_func, + self.attention_softmax_in_fp32, + coeff) + + # Dropout. Note that for a single iteration, this layer will generate + # different outputs on different number of parallel partitions but + # on average it should not be partition dependent. + self.attention_dropout = torch.nn.Dropout(config.attention_dropout) if config.attention_dropout != 0 else None + + def forward(self, query_layer, key_layer, + value_layer, attention_mask): + + # =================================== + # Raw attention scores. [b, np, s, s] + # =================================== + + # [b, np, sq, sk] + output_size = (query_layer.size(1), + query_layer.size(2), + query_layer.size(0), + key_layer.size(0)) + + # [sq, b, np, hn] -> [sq, b * np, hn] + query_layer = query_layer.view(output_size[2], + output_size[0] * output_size[1], -1) + # [sk, b, np, hn] -> [sk, b * np, hn] + key_layer = key_layer.view(output_size[3], + output_size[0] * output_size[1], -1) + + # preallocting input tensor: [b * np, sq, sk] + matmul_input_buffer = parallel_state.get_global_memory_buffer().get_tensor( + (output_size[0]*output_size[1], output_size[2], output_size[3]), + query_layer.dtype, "mpu") + + # Raw attention scores. [b * np, sq, sk] + matmul_result = torch.baddbmm( + matmul_input_buffer, + query_layer.transpose(0, 1), # [b * np, sq, hn] + key_layer.transpose(0, 1).transpose(1, 2), # [b * np, hn, sk] + beta=0.0, alpha=(1.0/self.norm_factor)) + + # change view to [b, np, sq, sk] + attention_scores = matmul_result.view(*output_size) + + # =========================== + # Attention probs and dropout + # =========================== + + # attention scores and attention mask [b, np, sq, sk] + attention_probs = self.scale_mask_softmax(attention_scores, + attention_mask) + + if self.attention_dropout is not None: + # This is actually dropping out entire tokens to attend to, which might + # seem a bit unusual, but is taken from the original Transformer paper. + if not self.sequence_parallel: + with tensor_parallel.get_cuda_rng_tracker().fork(): + attention_probs = self.attention_dropout(attention_probs) + else: + attention_probs = self.attention_dropout(attention_probs) + + # ========================= + # Context layer. [sq, b, hp] + # ========================= + + # value_layer -> context layer. + # [sk, b, np, hn] --> [b, np, sq, hn] + + # context layer shape: [b, np, sq, hn] + output_size = (value_layer.size(1), + value_layer.size(2), + query_layer.size(0), + value_layer.size(3)) + + # change view [sk, b * np, hn] + value_layer = value_layer.view(value_layer.size(0), + output_size[0] * output_size[1], -1) + + # change view [b * np, sq, sk] + attention_probs = attention_probs.view(output_size[0] * output_size[1], + output_size[2], -1) + + # matmul: [b * np, sq, hn] + context_layer = torch.bmm(attention_probs, value_layer.transpose(0, 1)) + + # change view [b, np, sq, hn] + context_layer = context_layer.view(*output_size) + + # [b, np, sq, hn] --> [sq, b, np, hn] + context_layer = context_layer.permute(2, 0, 1, 3).contiguous() + + # [sq, b, np, hn] --> [sq, b, hp] + new_context_layer_shape = context_layer.size()[:-2] + \ + (self.hidden_size_per_partition,) + context_layer = context_layer.view(*new_context_layer_shape) + + return context_layer + + +class FlashSelfAttention(torch.nn.Module): + """Implement the scaled dot product attention with softmax. + Arguments + --------- + softmax_scale: The temperature to use for the softmax attention. + (default: 1/sqrt(d_keys) where d_keys is computed at + runtime) + attention_dropout: The dropout rate to apply to the attention + (default: 0.0) + """ + def __init__(self, causal=False, softmax_scale=None, attention_dropout=0.0, + device=None, dtype=None): + super().__init__() + assert flash_attn_unpadded_func is not None or flash_attn_varlen_func is not None or flash_attn_builder is not None, \ + ('Please install FlashAttention first, e.g., with pip install flash-attn or implement your own flash attention') + assert rearrange is not None, 'Please install einops first, e.g., with pip install einops' + self.causal = causal + self.softmax_scale = softmax_scale + self.dropout_p = attention_dropout + + # Use FlashAttention-2 when args.use_flash_attn_v2 is True + args = get_args() + self.flash_attn_func = flash_attn_varlen_func if args.use_flash_attn_v2 else flash_attn_unpadded_func + + def forward(self, q, k, v): + """Implements the multihead softmax attention. + Arguments + --------- + q, k, v: The tensor containing the query, key, and value. (B, S, H, D) + """ + + assert all((i.dtype in [torch.float16, torch.bfloat16] for i in (q,k,v))) + assert all((get_accelerator().on_accelerator(i) for i in (q, k, v))) + # if get_accelerator().device_name() == 'cuda': + # assert all((i.is_cuda for i in (q,k,v))) + # else: + # assert all((i.is_xpu for i in (q,k,v))) + + batch_size, seqlen_q = q.shape[0], q.shape[1] + seqlen_k = k.shape[1] + + if get_accelerator().device_name() == 'cuda': + # goes for cuda device + q, k, v = [rearrange(x, 'b s ... -> (b s) ...') for x in [q, k, v]] + cu_seqlens_q = torch.arange(0, (batch_size + 1) * seqlen_q, step=seqlen_q, dtype=torch.int32, + device=q.device) + else: + # goes for other device + q, k, v = [rearrange(x, 'b s h d -> b h s d').contiguous() for x in [q, k, v]] + + if self.training: + # during training q,k,v always have same seqlen + assert seqlen_k == seqlen_q + + is_causal = self.causal + cu_seqlens_k = cu_seqlens_q if get_accelerator().device_name() == 'cuda' else None + dropout_p = self.dropout_p + else: + # turn off FA causal mask after first inference autoregressive iteration + # only on first autoregressive step q,k,v have same seqlen + is_causal = seqlen_q == seqlen_k + cu_seqlens_k = torch.arange(0, (batch_size + 1) * seqlen_k, step=seqlen_k, dtype=torch.int32, + device=q.device) if get_accelerator().device_name() == 'cuda' else None + dropout_p = 0 + + output = self.flash_attn_func( + q, k, v, cu_seqlens_q, cu_seqlens_k, seqlen_q, seqlen_k, + dropout_p, + softmax_scale=self.softmax_scale, causal=is_causal + ) if get_accelerator().device_name() == 'cuda' else flash_attn_builder.flash_attn_func( + q, k, v, self.dropout_p, self.softmax_scale, is_causal + ) + + output = rearrange(output, '(b s) ... -> b s ...', b=batch_size) if get_accelerator().device_name() == 'cuda' else rearrange( + output, 'b h s d -> b s h d').contiguous() + return output + +class FlashSelfAttentionTriton(torch.nn.Module): + """Implement the scaled dot product attention with softmax. + Arguments + --------- + softmax_scale: The temperature to use for the softmax attention. + (default: 1/sqrt(d_keys) where d_keys is computed at + runtime) + attention_dropout: The dropout rate to apply to the attention + (default: 0.0) + """ + def __init__(self, causal=False, softmax_scale=None, attention_dropout=0.0, + device=None, dtype=None): + super().__init__() + assert flash_attn_func is not None, ('Triton version of FlashAttention is not installed.') + assert rearrange is not None, 'Please install einops first, e.g., with pip install einops' + self.causal = causal + self.softmax_scale = softmax_scale + self.dropout_p = attention_dropout + + def forward(self, q, k, v): + """Implements the multihead softmax attention. + Arguments + --------- + q, k, v: The tensor containing the query, key, and value. (B, S, H, D) + """ + + assert q.dtype in [torch.float16, torch.bfloat16] + assert q.is_cuda + q, k, v = [rearrange(x, 's b ... -> b s ...').contiguous() + for x in (q, k, v)] + + output = flash_attn_func(q, k, v, None, self.causal) + output = rearrange(output, 'b s h d -> s b (h d)').contiguous() + return output + + +class HabanaFlashSelfAttention(MegatronModule): + + def __init__(self, config, attn_mask_type=AttnMaskType.padding): + super(HabanaFlashSelfAttention, self).__init__() + assert hthpu is not None, "Failed to import hthpu" + assert FusedSDPA is not None, "Failed to import FusedSDPA" + self.attn_mask_type = attn_mask_type + self.attention_dropout_p = config.attention_dropout + self.use_fused_sdpa = config.use_fused_sdpa + self.use_fused_sdpa_with_recompute = config.use_fused_sdpa_with_recompute + + # Per attention head and per partition values. + seq_parallel_world_size = 1 + if parallel_state.sequence_parallel_is_initialized(): + seq_parallel_world_size = parallel_state.get_sequence_parallel_world_size() + world_size = seq_parallel_world_size if seq_parallel_world_size > 1 else parallel_state.get_tensor_model_parallel_world_size() + + projection_size = config.kv_channels * config.num_attention_heads + self.hidden_size_per_partition = core.utils.divide(projection_size, + world_size) + + def forward(self, query_layer, key_layer, + value_layer, attention_mask): + # [sq, b, np, hn] -> [b, np, sq, hn] + q, k, v = [x.transpose(0, 1).transpose(1, 2) for x in [query_layer, key_layer, value_layer]] + causal = True + scale = None + attn_mask = None + with hthpu.sdp_kernel(enable_recompute=self.use_fused_sdpa_with_recompute): + context_layer = FusedSDPA.apply(q, k, v, attn_mask, self.attention_dropout_p, causal, scale) + + # [b, np, sq, hn] --> [sq, b, np, hn] + context_layer = context_layer.permute(2, 0, 1, 3).contiguous() + + # [sq, b, np, hn] --> [sq, b, hp] + new_context_layer_shape = context_layer.size()[:-2] + \ + (self.hidden_size_per_partition,) + context_layer = context_layer.view(*new_context_layer_shape) + + return context_layer + + +class ParallelAttention(MegatronModule): + """Parallel self-attention layer abstract class. + + Self-attention layer takes input with size [s, b, h] + and returns output of the same size. + """ + + def __init__(self, config, layer_number, + attention_type=AttnType.self_attn, + attn_mask_type=AttnMaskType.padding): + super(ParallelAttention, self).__init__() + args = get_args() + self.layer_number = max(1, layer_number) + self.attention_type = attention_type + self.attn_mask_type = attn_mask_type + self.params_dtype = config.params_dtype + self.sequence_parallel = config.sequence_parallel + self.num_attention_heads = config.num_attention_heads + self.num_key_value_heads = config.num_key_value_heads + # TODO - Remove self.attention_dropout usage when SW-172239 is solved + self.attention_dropout = config.attention_dropout + self.use_gqa = (self.num_attention_heads != self.num_key_value_heads) + + self.use_flash_attn = (args.use_flash_attn_v1 or args.use_flash_attn_triton or args.use_flash_attn_v2) \ + and attention_type == AttnType.self_attn \ + and self.attn_mask_type == AttnMaskType.causal + self.use_flash_attn_triton = args.use_flash_attn_triton + self.use_fused_sdpa = config.use_fused_sdpa + if self.use_flash_attn: + global flash_attn_builder + try: + flash_attn_builder = FlashAttentionBuilder().load() + except TypeError: + flash_attn_builder = None + + if args.use_flash_attn_v1: + assert flash_attn_unpadded_func != None or flash_attn_builder != None, ("Cannot import FlashAttention v1 " + "and Cannot find FlashAttention Builder") + if args.use_flash_attn_v2: + assert flash_attn_varlen_func != None, "Cannot import FlashAttention v2 " + if args.use_flash_attn_triton: + assert flash_attn_func != None, "Cannot import FlashAttention triton " + + assert attention_type == AttnType.self_attn, ('FlashAttention code path only supports ' + 'self-attention for now') + assert self.attn_mask_type == AttnMaskType.causal, ('FlashAttention code path only ' + 'supports causal mask for now') + if rearrange is None: + raise ImportError('einops is not installed, please install with pip install einops') + + projection_size = config.kv_channels * config.num_attention_heads + + # Per attention head and per partition values. + world_size = parallel_state.get_tensor_model_parallel_world_size() + self.hidden_size_per_attention_head = core.utils.divide( + projection_size, config.num_attention_heads) + self.num_attention_heads_per_partition = core.utils.divide( + config.num_attention_heads, world_size) + + # Per GQA head and per partition values + self.num_key_value_heads_per_partition = core.utils.divide( + config.num_key_value_heads, world_size) + self.num_key_value_groups = core.utils.divide( + config.num_attention_heads, config.num_key_value_heads) + kv_projection_size = config.kv_channels * config.num_key_value_heads + assert self.hidden_size_per_attention_head == core.utils.divide( + kv_projection_size, config.num_key_value_heads) + + # Strided linear layer. + if attention_type == AttnType.self_attn: + self.query_key_value = tensor_parallel.ColumnParallelLinear( + config.hidden_size, + projection_size + 2 * kv_projection_size, + config=config, + init_method=config.init_method, + bias=args.add_bias_linear, + gather_output=False) + else: + assert attention_type == AttnType.cross_attn + self.query = tensor_parallel.ColumnParallelLinear( + config.hidden_size, + projection_size, + config=config, + init_method=config.init_method, + bias=config.add_bias_linear, + gather_output=False) + + + self.key_value = tensor_parallel.ColumnParallelLinear( + config.hidden_size, + 2 * projection_size, + config=config, + init_method=config.init_method, + bias=config.add_bias_linear, + gather_output=False) + + # Currently FlashAttention only works with causal mask + if self.use_flash_attn_triton: + local_attn = FlashSelfAttentionTriton(causal=True, attention_dropout=args.attention_dropout) + elif self.use_flash_attn: + local_attn = FlashSelfAttention(causal=True, attention_dropout=config.attention_dropout) + elif self.use_fused_sdpa: + local_attn = HabanaFlashSelfAttention(config, self.attn_mask_type) + else: + local_attn = CoreAttention(self.layer_number, config, self.attn_mask_type) + + self.enable_ds_sequence_parallel = parallel_state.get_sequence_parallel_world_size() > 1 \ + or args.force_ds_sequence_parallel + if self.enable_ds_sequence_parallel: + assert dist_attn_supported, 'Distributed attention is not supported in this DeepSpeed version' + assert args.num_attention_heads % parallel_state.get_sequence_parallel_world_size() == 0 + self.dist_attn = DistributedAttention(local_attn, parallel_state.get_sequence_parallel_group()) + else: + if self.use_flash_attn: + self.core_attention_flash = local_attn + else: + self.core_attention = local_attn + self.checkpoint_core_attention = config.recompute_granularity == 'selective' + + # Output. + self.dense = tensor_parallel.RowParallelLinear( + projection_size, + config.hidden_size, + config=config, + init_method=config.output_layer_init_method, + bias=args.add_bias_linear, + input_is_parallel=True, + skip_bias_add=True) + + + def _checkpointed_attention_forward(self, query_layer, key_layer, + value_layer, attention_mask, + rotary_pos_emb=None): + """Forward method with activation checkpointing.""" + def custom_forward(*inputs): + query_layer = inputs[0] + key_layer = inputs[1] + value_layer = inputs[2] + attention_mask = inputs[3] + output_ = self.core_attention(query_layer, key_layer, + value_layer, attention_mask) + return output_ + + q_pos_emb, k_pos_emb = (None, None) if rotary_pos_emb is None \ + else rotary_pos_emb + + hidden_states = tensor_parallel.checkpoint( + custom_forward, + False, query_layer, key_layer, value_layer, attention_mask, + q_pos_emb, k_pos_emb) + + return hidden_states + + def _allocate_memory(self, inference_max_sequence_len, batch_size): + return torch.empty( + inference_max_sequence_len, + batch_size, + self.num_attention_heads_per_partition, + self.hidden_size_per_attention_head, + dtype=self.params_dtype, + device=get_accelerator().current_device_name()) + + def repeat_kv(self, hidden_states, n_rep): + slen, batch, num_key_value_heads_per_partition, head_dim = hidden_states.shape + if n_rep == 1: + return hidden_states + elif num_key_value_heads_per_partition == 1: + # If no of KV heads is 1 then just perform expand operation + # instead of unsqueeze, expand and reshape to match query states. + return hidden_states.expand(slen, batch, n_rep, head_dim) + else: + hidden_states = hidden_states[:, :, :, None, :].expand( + slen, batch, num_key_value_heads_per_partition, n_rep, head_dim) + return hidden_states.reshape(slen, batch, + num_key_value_heads_per_partition * n_rep, + head_dim) + + def split_tensor(self, mixed_x_layer): + query_layer, key_layer, value_layer = torch.split(mixed_x_layer, [self.num_key_value_groups, 1, 1], dim=-2) + query_layer = query_layer.reshape(mixed_x_layer.shape[:2] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)) + key_layer = torch.squeeze(key_layer, -2) + value_layer = torch.squeeze(value_layer, -2) + + return query_layer, key_layer, value_layer + + def forward(self, hidden_states, attention_mask, + encoder_output=None, inference_params=None, + rotary_pos_emb=None): + # hidden_states: [sq, b, h] + + # ================================================= + # Pre-allocate memory for key-values for inference. + # ================================================= + is_first_step = False + if inference_params: + if self.layer_number not in inference_params.key_value_memory_dict: + inf_max_seq_len = inference_params.max_sequence_len + inf_max_batch_size = inference_params.max_batch_size + inference_key_memory = self._allocate_memory( + inf_max_seq_len, inf_max_batch_size) + inference_value_memory = self._allocate_memory( + inf_max_seq_len, inf_max_batch_size) + inference_params.key_value_memory_dict[self.layer_number] = ( + inference_key_memory, inference_value_memory) + is_first_step = True + else: + inference_key_memory, inference_value_memory = \ + inference_params.key_value_memory_dict[self.layer_number] + + # ===================== + # Query, Key, and Value + # ===================== + + if self.attention_type == AttnType.self_attn: + # Attention heads [sq, b, h] --> [sq, b, ((nq + 2 * nkv) * hn)] + mixed_x_layer, _ = self.query_key_value(hidden_states) + + # [sq, b, ((nq + 2 * nkv) * hn)] --> [sq, b, nkv, (nq // nkv + 2), hn] + new_tensor_shape = mixed_x_layer.size()[:-1] + \ + (-1, (self.num_key_value_groups + 2), + self.hidden_size_per_attention_head) + mixed_x_layer = mixed_x_layer.view(*new_tensor_shape) + + # [sq, b, nkv, (nq // nkv + 2), hn] --> 3 [sq, b, np, hn] + (query_layer, + key_layer, + value_layer) = self.split_tensor(mixed_x_layer) + + # Repeat kv ; fused SPDA internally handles it + # TODO - Remove self.attention_dropout check when SW-172239 is solved + if self.use_gqa and (not self.use_fused_sdpa or self.attention_dropout != 0): + key_layer = self.repeat_kv(key_layer, self.num_key_value_groups) + value_layer = self.repeat_kv(value_layer, + self.num_key_value_groups) + else: + assert not self.use_gqa, 'GQA + cross-attn not tested yet' + + # Attention heads [sk, b, h] --> [sk, b, (np * 2 * hn)] + mixed_kv_layer, _ = self.key_value(encoder_output) + + # [sk, b, (np * 2 * hn)] --> [sk, b, np, 2 * hn] + new_tensor_shape = mixed_kv_layer.size()[:-1] + \ + (self.num_attention_heads_per_partition, + 2 * self.hidden_size_per_attention_head) + mixed_kv_layer = mixed_kv_layer.view(*new_tensor_shape) + + # [sk, b, np, 2 * hn] --> 2 [sk, b, np, hn] + (key_layer, + value_layer) = tensor_parallel.split_tensor_along_last_dim(mixed_kv_layer, 2) + + # Attention head [sq, b, h] --> [sq, b, hp] + query_layer, _ = self.query(hidden_states) + # [sq, b, hp] --> [sq, b, np, hn] + new_tensor_shape = query_layer.size()[:-1] + \ + (self.num_attention_heads_per_partition, + self.hidden_size_per_attention_head) + query_layer = query_layer.view(*new_tensor_shape) + + # ================================== + # Adjust key and value for inference + # ================================== + + # duplicate the pos_emb for self attention + if rotary_pos_emb is not None: + if isinstance(rotary_pos_emb, tuple): + rotary_pos_emb = rotary_pos_emb + else: + rotary_pos_emb = ((rotary_pos_emb,) * 2) + + if inference_params: + batch_start = inference_params.batch_size_offset + batch_end = batch_start + key_layer.size(1) + assert batch_end <= inference_key_memory.size(1) + sequence_start = inference_params.sequence_len_offset + sequence_end = sequence_start + key_layer.size(0) + assert sequence_end <= inference_key_memory.size(0) + # Copy key and values. + inference_key_memory[sequence_start:sequence_end, + batch_start:batch_end, ...] = key_layer + inference_value_memory[sequence_start:sequence_end, + batch_start:batch_end, ...] = value_layer + key_layer = inference_key_memory[ + :sequence_end, batch_start:batch_end, ...] + value_layer = inference_value_memory[ + :sequence_end, batch_start:batch_end, ...] + + + # adjust the key rotary positional embedding + if rotary_pos_emb is not None: + q_pos_emb, k_pos_emb = rotary_pos_emb + # need to cross check this condition during inference + # if not set_inference_key_value_memory: + if not is_first_step: + # In inference, we compute one token at a time. + # Select the correct positional embedding + # (only the last token in the sequence) + q_pos_emb = q_pos_emb[sequence_end - 1 : sequence_end] + else: + # In the first forward pass of inference, + # we use the entire provided prefix. + # q_pos_emb here has the rope embeddings of the entire + # prefix + to-be-generated output so + # we slice to just the prefix. + q_pos_emb = q_pos_emb[:sequence_end, :, :, :] + k_pos_emb = k_pos_emb[:sequence_end, :, :, :] + rotary_pos_emb = (q_pos_emb, k_pos_emb) + + + # ================================== + # core attention computation + # ================================== + + # apply relative positional encoding (rotary embedding) + if rotary_pos_emb is not None: + q_pos_emb, k_pos_emb = rotary_pos_emb + query_layer = apply_rotary_pos_emb(query_layer, q_pos_emb) + key_layer = apply_rotary_pos_emb(key_layer, k_pos_emb) + # TODO, can apply positional embedding to value_layer so it has + # absolute positional embedding. + # otherwise, only relative positional embedding takes effect + # value_layer = apply_rotary_pos_emb(value_layer, k_pos_emb) + + if self.enable_ds_sequence_parallel: + if self.use_flash_attn: + if not self.use_flash_attn_triton: + query_layer, key_layer, value_layer = [rearrange(x, 's b ... -> b s ...').contiguous() + for x in (query_layer, key_layer, value_layer)] + + context_layer = self.dist_attn(query_layer, key_layer, value_layer) + + if not self.use_flash_attn_triton: + context_layer = rearrange(context_layer, 'b s h d -> s b (h d)').contiguous() + else: + context_layer = self.dist_attn(query_layer, key_layer, value_layer, attention_mask) + else: + if self.use_flash_attn: + if not self.use_flash_attn_triton: + query_layer, key_layer, value_layer = [rearrange(x, 's b ... -> b s ...').contiguous() + for x in (query_layer, key_layer, value_layer)] + + if self.sequence_parallel: + context_layer = self.core_attention_flash(query_layer, key_layer, value_layer) + else: + with tensor_parallel.get_cuda_rng_tracker().fork(): + context_layer = self.core_attention_flash(query_layer, key_layer, value_layer) + + if not self.use_flash_attn_triton: + context_layer = rearrange(context_layer, 'b s h d -> s b (h d)').contiguous() + else: + if self.checkpoint_core_attention: + context_layer = self._checkpointed_attention_forward( + query_layer, key_layer, value_layer, attention_mask) + else: + context_layer = self.core_attention( + query_layer, key_layer, value_layer, attention_mask) + + # ================= + # Output. [sq, b, h] + # ================= + + output, bias = self.dense(context_layer) + + return output, bias + + +def bias_dropout_add(x, bias, residual, prob, training): + # type: (Tensor, Optional[Tensor], Tensor, float, bool) -> Tensor + if bias is not None: + x = x + bias + if prob == 0: + out = x + else: + out = torch.nn.functional.dropout(x, p=prob, training=training) + out = residual + out + return out + + +def get_bias_dropout_add(training): + def _bias_dropout_add(x, bias, residual, prob): + return bias_dropout_add(x, bias, residual, prob, training) + return _bias_dropout_add + + +@torch.jit.script +def bias_dropout_add_fused_train(x: torch.Tensor, + bias: Optional[torch.Tensor], + residual: torch.Tensor, + prob: float) -> torch.Tensor: + return bias_dropout_add(x, bias, residual, prob, True) + + +@torch.jit.script +def bias_dropout_add_fused_inference(x: torch.Tensor, + bias: Optional[torch.Tensor], + residual: torch.Tensor, + prob: float) -> torch.Tensor: + return bias_dropout_add(x, bias, residual, prob, False) + + +class ParallelTransformerLayer(MegatronModule): + """A single transformer layer. + + Transformer layer takes input with size [s, b, h] and returns an + output of the same size. + """ + + def __init__(self, config, + layer_number, layer_type=LayerType.encoder, + self_attn_mask_type=AttnMaskType.padding, + drop_path_rate=0., num_experts=1): + # retriever=None): + args = get_args() + + super(ParallelTransformerLayer, self).__init__() + self.layer_number = layer_number + self.layer_type = layer_type + + self.apply_residual_connection_post_layernorm \ + = config.apply_residual_connection_post_layernorm + + self.bf16 = config.bf16 + self.fp32_residual_connection = config.fp32_residual_connection + + # Layernorm on the input data. + if args.normalization == 'layernorm': + if get_accelerator().device_name() in ['cuda', 'hpu']: + self.input_layernorm = LayerNorm( + config.hidden_size, + eps=config.layernorm_epsilon, + no_persist_layer_norm=args.no_persist_layer_norm, + sequence_parallel=config.sequence_parallel, + apply_layernorm_1p=args.apply_layernorm_1p, + mem_efficient_ln=args.mem_efficient_ln) + else: + self.input_layernorm = LayerNorm( + config.hidden_size, + eps=config.layernorm_epsilon) + else: + self.input_layernorm = MixedFusedRMSNorm(config.hidden_size, + config.layernorm_epsilon, + sequence_parallel=config.sequence_parallel) + # Self attention. + self.self_attention = ParallelAttention( + config, + layer_number, + attention_type=AttnType.self_attn, + attn_mask_type=self_attn_mask_type) + self.hidden_dropout = config.hidden_dropout + self.bias_dropout_fusion = config.bias_dropout_fusion + self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0.0 else None + + # Layernorm on the attention output + if args.normalization == 'layernorm': + if get_accelerator().device_name() in ['cuda', 'hpu']: + self.post_attention_layernorm = LayerNorm( + config.hidden_size, + eps=config.layernorm_epsilon, + no_persist_layer_norm=not config.persist_layer_norm, + sequence_parallel=config.sequence_parallel, + apply_layernorm_1p=args.apply_layernorm_1p, + mem_efficient_ln=args.mem_efficient_ln) + else: + self.post_attention_layernorm = LayerNorm( + config.hidden_size, + eps=config.layernorm_epsilon) + else: + self.post_attention_layernorm = MixedFusedRMSNorm(config.hidden_size, + config.layernorm_epsilon, + sequence_parallel=config.sequence_parallel) + # Cross attention. + if self.layer_type in (LayerType.decoder, + LayerType.retro_decoder, + LayerType.retro_decoder_with_retriever, + LayerType.retro_encoder): + self.inter_attention = ParallelAttention( + config, + layer_number, + attention_type=AttnType.cross_attn) + # Layernorm on the attention output. + if args.normalization == 'layernorm': + self.post_inter_attention_layernorm = LayerNorm( + config.hidden_size, + eps=config.layernorm_epsilon, + no_persist_layer_norm=not config.persist_layer_norm, + sequence_parallel=config.sequence_parallel, + apply_layernorm_1p=args.apply_layernorm_1p, + mem_efficient_ln=args.mem_efficient_ln) + else: + self.post_inter_attention_layernorm = MixedFusedRMSNorm(config.hidden_size, + config.layernorm_epsilon, + sequence_parallel=config.sequence_parallel) + + # MLP + self.num_experts = num_experts + if args.num_experts_switch is not None: + self.mlp = SwitchMLP(config) # Megatron-LM's MoE + else: + if self.num_experts <= 1: # dense, not MoE + self.mlp = ParallelMLP(config) + else: # DeepSpeed's MoE + enable_expert_tensor_parallelism = args.enable_expert_tensor_parallelism + self.mlp = MoE(args.hidden_size, + ParallelMLP(config, + moe=True, + enable_expert_tensor_parallelism=enable_expert_tensor_parallelism), + num_experts=self.num_experts, + ep_size=args.moe_expert_parallel_size, + k=args.topk, + use_residual=(args.mlp_type == 'residual'), + capacity_factor=args.moe_train_capacity_factor, + eval_capacity_factor=args.moe_eval_capacity_factor, + min_capacity=args.moe_min_capacity, + drop_tokens=args.moe_token_dropping, use_tutel=args.use_tutel, + enable_expert_tensor_parallelism=enable_expert_tensor_parallelism) + + # Set bias+dropout+add fusion grad_enable execution handler. + TORCH_MAJOR = int(torch.__version__.split('.')[0]) + TORCH_MINOR = int(torch.__version__.split('.')[1]) + use_nvfuser = TORCH_MAJOR > 1 or (TORCH_MAJOR == 1 and TORCH_MINOR >= 10) + self.bias_dropout_add_exec_handler = \ + nullcontext if use_nvfuser else torch.enable_grad + + if args.retro_add_retriever: + retro_args = get_retro_args() + self.retro_num_neighbors = args.retro_num_neighbors + self.retro_chunk_length = retro_args.retro_gpt_chunk_length + self.retro_retrieved_length = retro_args.retro_gpt_retrieved_length + + # Retriever (bi-directional transformer with cross attention) + if layer_type == LayerType.retro_decoder_with_retriever: + self.retriever = ParallelTransformer( + config=config, + model_type=ModelType.retro_encoder, + self_attn_mask_type=AttnMaskType.padding, + pre_process=True, + post_process=False, + ) + self._retriever_key = 'retriever' + else: + self.retriever = None + + def default_decoder_cross_attention(self, + encoder_output, + enc_dec_attn_mask, + layernorm_input, + layernorm_output, + bias_dropout_add_func): + '''Cross attention for a standard encoder-decoder model.''' + + # Attention. + attention_output, attention_bias = \ + self.inter_attention(layernorm_output, + enc_dec_attn_mask, + encoder_output=encoder_output) + + # Residual connection. + if self.apply_residual_connection_post_layernorm: + residual = layernorm_output + else: + residual = layernorm_input + + if attention_bias is not None: + attention_bias = attention_bias.expand_as(residual) + + # Bias-dropout-add. + with self.bias_dropout_add_exec_handler(): + layernorm_input = bias_dropout_add_func( + attention_output, + attention_bias, + residual, + self.hidden_dropout) + + # Layer norm. + layernorm_output = self.post_inter_attention_layernorm(layernorm_input) + + return layernorm_input, layernorm_output + + def retro_encoder_cross_attention(self, + retriever_output, + layernorm_input, + layernorm_output, + bias_dropout_add_func): + """Cross attention for Retro encoder. + + Notation: + ns : Sequence length. + bs : Batch size. + d : Hidden size. + l : Number of chunks per sample (i.e., seq_length/chunk_length). + k : Number of neighbors. + r : Number of retrieved tokens (neighbors + continuation). + """ + + ns, bs, d = layernorm_output.shape # [r, bs * l * k, d] + + # Divide sequence dimension into chunks. + chunked_outputs = layernorm_output.reshape(self.retro_retrieved_length, + -1, + self.retro_num_neighbors, + d) + chunked_outputs_before_layer_norm = \ + layernorm_input.reshape(self.retro_retrieved_length, -1, + self.retro_num_neighbors, d) # [r, bs*l, k, d] + + # Per-chunk attention. + layernorm_inputs = [] + layernorm_outputs = [] + for k in range(self.retro_num_neighbors): + + # Attention. + chunked_output = chunked_outputs[:,:,k].contiguous() + attention_output, attention_bias = \ + self.inter_attention( + chunked_output, # Q (neighbor embedding) + None, + encoder_output=retriever_output) # K, V (hidden act) + + # Residual connection. + if self.apply_residual_connection_post_layernorm: + residual = chunked_output + else: + residual = chunked_outputs_before_layer_norm[:,:,k] + + # Re-enable torch grad to enable fused optimization. + with torch.enable_grad(): + layernorm_input = bias_dropout_add_func( + attention_output, + None if attention_bias is None else attention_bias.expand_as(residual), + residual, + self.hidden_dropout) + layernorm_inputs.append(layernorm_input) + + # Layer norm. + layernorm_output = \ + self.post_inter_attention_layernorm(layernorm_input) + layernorm_outputs.append(layernorm_output) + + # Concatenate layer norms. + # layernorm_input : [r, k * bs * l, d] + # layernorm_output : [r, k * bs * l, d] + layernorm_input = \ + torch.stack(layernorm_inputs, dim=1).reshape(ns, bs, d) + layernorm_output = \ + torch.stack(layernorm_outputs, dim=1).reshape(ns, bs, d) + + return layernorm_input, layernorm_output + + def retro_decoder_cross_attention(self, + retriever_input, + retriever_output, + retriever_attn_mask, + layernorm_input, + layernorm_output, + inference_params, + bias_dropout_add_func): + """Cross attention for Retro decoder. + + Notation: + ns : Sequence length. + bs : Batch size. + d : Hidden size. + l : Number of chunks per sample (i.e., seq_length/chunk_length). + m : Number of tokens per chunk. + k : Number of neighbors. + r : Number of retrieved tokens (neighbors + continuation). + """ + + ns, bs, d = layernorm_output.shape + l = int(np.ceil(ns / self.retro_chunk_length)) + + # Retrieve neighbors. + if self.layer_type == LayerType.retro_decoder_with_retriever: + first_ns = ns % self.retro_chunk_length + if first_ns > 0: + raise Exception("test this case.") + first_chunk, rest_chunk = \ + layernorm_output[:first_ns], layernorm_output[first_ns:] + first_chunk = torch.nn.functional.pad( + first_chunk, + (0, 0, 0, 0, 0, self.retro_chunk_length - first_ns), + 'constant', + 0) + chunked_output = \ + torch.cat((first_chunk, rest_chunk), dim=0) # [l * m, bs, d] + else: + chunked_output = layernorm_output # [l * m, bs, d] + chunked_output = chunked_output \ + .reshape(l, self.retro_chunk_length, bs, d) \ + .permute(1, 2, 0, 3) \ + .reshape(self.retro_chunk_length, bs * l, d) \ + .contiguous() + + # Get Encoder Output + retriever_output = self.retriever( + hidden_states=retriever_input, + attention_mask=retriever_attn_mask, + retriever_output=chunked_output, + retriever_attn_mask=retriever_attn_mask, + inference_params=inference_params) # [r, k * bs * l , d] + retriever_output = retriever_output.reshape( + self.retro_retrieved_length * self.retro_num_neighbors, bs * l, d) # [r * k, bs * l, d] + + # Chunks. + pad = (ns - 1) % self.retro_chunk_length + attending_chunks = layernorm_output[pad:] + padded_chunks = torch.nn.functional.pad( + attending_chunks, + (0, 0, 0, 0, 0, self.retro_chunk_length - 1), + 'constant', 0) + padded_chunked_output = padded_chunks \ + .reshape(l, self.retro_chunk_length, bs, d) \ + .permute(1, 2, 0, 3) + padded_chunked_output = padded_chunked_output.reshape( + self.retro_chunk_length, bs * l, d).contiguous() + + # Encoder output. + attention_output, attention_bias = \ + self.inter_attention(padded_chunked_output, + None, + encoder_output=retriever_output) + + # Residual connection. + if self.apply_residual_connection_post_layernorm: + residual = layernorm_output + else: + residual = layernorm_input + + # Re-enable torch grad to enable fused optimization. + with torch.enable_grad(): + layernorm_input = bias_dropout_add_func( + attention_output, + None if attention_bias is None else attention_bias.expand_as(attention_output), + torch.zeros_like(attention_output), + self.hidden_dropout) + layernorm_input = layernorm_input \ + .reshape(self.retro_chunk_length, bs, l, d) \ + .permute(2, 0, 1, 3) # [l, m, bs, d] + layernorm_input = layernorm_input.reshape(self.retro_chunk_length * l, bs, d) + layernorm_input = torch.nn.functional.pad( + layernorm_input, + (0, 0, 0, 0, pad, 0), + 'constant', 0)[:ns] # [ns, b, d] + layernorm_input = layernorm_input + residual + + # Layer norm post the decoder attention + layernorm_output = self.post_inter_attention_layernorm(layernorm_input) + + return retriever_output, layernorm_input, layernorm_output + + def forward(self, hidden_states, attention_mask=None, + encoder_output=None, enc_dec_attn_mask=None, + retriever_input=None, + retriever_output=None, + retriever_attn_mask=None, + inference_params=None, + rotary_pos_emb=None): + # hidden_states: [s, b, h] + + # Layer norm at the beginning of the transformer layer. + layernorm_output = self.input_layernorm(hidden_states) + + # Self attention. + attention_output, attention_bias = \ + self.self_attention( + layernorm_output, + attention_mask, + inference_params=inference_params, + rotary_pos_emb=rotary_pos_emb) + + # Residual connection. + if self.apply_residual_connection_post_layernorm: + residual = layernorm_output + else: + residual = hidden_states + + if self.drop_path is None: + # jit scripting for a nn.module (with dropout) is not + # trigerring the fusion kernel. For now, we use two + # different nn.functional routines to account for varying + # dropout semantics during training and inference phases. + if self.bias_dropout_fusion: + if self.training: + bias_dropout_add_func = bias_dropout_add_fused_train + else: + bias_dropout_add_func = bias_dropout_add_fused_inference + else: + bias_dropout_add_func = get_bias_dropout_add(self.training) + + if attention_bias is not None: + attention_bias = attention_bias.expand_as(residual) + with self.bias_dropout_add_exec_handler(): + layernorm_input = bias_dropout_add_func( + attention_output, + attention_bias, + residual, + self.hidden_dropout) + else: + out = torch.nn.functional.dropout(attention_output + attention_bias, + p=self.hidden_dropout, + training=self.training) + layernorm_input = residual + self.drop_path(out) + + # Layer norm post the self attention. + layernorm_output = self.post_attention_layernorm(layernorm_input) + + # Cross attention. + if self.layer_type == LayerType.encoder: + pass + elif self.layer_type == LayerType.decoder: + layernorm_input, layernorm_output = \ + self.default_decoder_cross_attention( + encoder_output, + enc_dec_attn_mask, + layernorm_input, + layernorm_output, + bias_dropout_add_func) + elif self.layer_type == LayerType.retro_encoder: + layernorm_input, layernorm_output = \ + self.retro_encoder_cross_attention( + retriever_output, + layernorm_input, + layernorm_output, + bias_dropout_add_func) + elif self.layer_type in (LayerType.retro_decoder, + LayerType.retro_decoder_with_retriever): + retriever_output, layernorm_input, layernorm_output = \ + self.retro_decoder_cross_attention( + retriever_input, + retriever_output, + retriever_attn_mask, + layernorm_input, + layernorm_output, + inference_params, + bias_dropout_add_func) + else: + raise Exception("Unsupported layer type, '%s'." % + self.layer_type.name) + + # MLP. + moe_loss = torch.tensor(0.0, device=layernorm_output.device, dtype=layernorm_output.dtype) + mlp_bias = torch.tensor(0.0, device=layernorm_output.device, dtype=layernorm_output.dtype) + + if self.num_experts == 1: + mlp_output, mlp_bias = self.mlp(layernorm_output) + else: + mlp_output, moe_loss, _ = self.mlp(layernorm_output) + + # Second residual connection. + if self.apply_residual_connection_post_layernorm: + residual = layernorm_output + else: + residual = layernorm_input + + if self.drop_path is None: + if mlp_bias is not None: + mlp_bias = mlp_bias.expand_as(residual) + with self.bias_dropout_add_exec_handler(): + output = bias_dropout_add_func( + mlp_output, + mlp_bias, + residual, + self.hidden_dropout) + + # Jit compiled function creates 'view' tensor. This tensor + # potentially gets saved in the MPU checkpoint function context, + # which rejects view tensors. While making a viewless tensor here + # won't result in memory savings (like the data loader, or + # p2p_communication), it serves to document the origin of this + # 'view' tensor. + output = core.utils.make_viewless_tensor(inp = output, + requires_grad = output.requires_grad, + keep_graph = True) + + else: + if mlp_bias is not None: + mlp_output = mlp_output + mlp_bias + out = torch.nn.functional.dropout(mlp_output, + p=self.hidden_dropout, + training=self.training) + output = residual + self.drop_path(out) + + if self.layer_type == LayerType.retro_decoder_with_retriever: + return output, retriever_output, moe_loss + else: + return output, moe_loss + + +class ParallelTransformerLayerPipe(ParallelTransformerLayer): + """Extends ParallelTransformerLayer to forward attention_mask through the pipeline. + + Forward has two usages that affect attention mask communication: + + 1) forward((input, attn_mask) , **kwargs) -> (output, mask) + When the attention mask is provided as the second positional + argument, typical pipeline behavior is used and both the output + *and* mask are returned in a tuple. This tuple is then forwarded + to the next stage in the pipeline. + + This version is useful if masks are dynamic. + + 2) forward(input, **kwargs) -> output + When the mask is static over all samples, it is advantageous to + cache the mask and avoid communicating it. + + If no mask is provided, the module will query `self._args.attn_mask` + for the mask and only return `super().forward(...)` + """ + def forward(self, inputs, **kwargs): + assert torch.is_tensor(inputs) or isinstance(inputs, tuple) + if not hasattr(self, '_args'): + self._args = get_args() + rotary_pos_emb = self._args.rotary_pos_emb if self._args.use_rotary_position_embeddings else None + if torch.is_tensor(inputs) or len(inputs) == 1: + # No attention mask forwarded, search for args.attn_mask + hidden_states, attention_mask = inputs, self._args.attn_mask + # HACK: currently MoE model does not support pipeline parallel, so + # here we just ignore the moe_loss returned by forward() + return super().forward(hidden_states, attention_mask, **kwargs, rotary_pos_emb=rotary_pos_emb)[0] + elif len(inputs) == 2: + # Attention mask is an activation. + hidden_states, attention_mask = inputs[0], inputs[1] + # HACK: currently MoE model does not support pipeline parallel, so + # here we just ignore the moe_loss returned by forward() + return super().forward(*inputs, **kwargs, rotary_pos_emb=rotary_pos_emb)[0], attention_mask + else: + raise RuntimeError('Received more inputs than understood.') + + +class NoopTransformerLayer(MegatronModule): + """A single 'no-op' transformer layer. + + The sole purpose of this layer is for when a standalone embedding layer + is used (i.e., args.standalone_embedding_stage == True). In this case, + zero transformer layers are assigned when pipeline rank == 0. Additionally, + when virtual pipeline rank >= 1, zero total model parameters are created + (virtual rank 0 contains the input embedding). This results in the model's + input and output tensors being the same, which causes an error when + performing certain memory optimiations on the output tensor (e.g., + deallocating it). Thus, this layer disconnects the input from the output + via a clone. Since ranks containing a no-op layer are generally under- + utilized (both compute and memory), there's no worry of any performance + degredation. + """ + + def __init__(self, layer_number): + super().__init__() + self.layer_number = layer_number + + def forward(self, hidden_states, attention_mask, + encoder_output=None, enc_dec_attn_mask=None, + inference_params=None): + return hidden_states.clone() + + +def _get_num_layers(args, model_type, is_decoder=False): + """Compute the number of transformer layers resident on the current rank.""" + is_encoder_and_decoder_model = (model_type == ModelType.encoder_and_decoder) + if model_type == ModelType.retro_encoder: + num_layers = args.retro_encoder_layers + elif parallel_state.get_pipeline_model_parallel_world_size() > 1: + if is_encoder_and_decoder_model: + assert args.pipeline_model_parallel_split_rank is not None + + # When a standalone embedding stage is used, a rank is taken from + # the encoder's ranks, to be used for the encoder's embedding + # layer. This way, the rank referenced by the 'split rank' remains + # the same whether or not a standalone embedding stage is used. + num_ranks_in_encoder = ( + args.pipeline_model_parallel_split_rank - 1 + if args.standalone_embedding_stage else + args.pipeline_model_parallel_split_rank + ) + num_ranks_in_decoder = args.transformer_pipeline_model_parallel_size - num_ranks_in_encoder + assert args.encoder_num_layers % num_ranks_in_encoder == 0, \ + 'encoder_num_layers (%d) must be divisible by number of ranks given to encoder (%d)' % (args.encoder_num_layers, num_ranks_in_encoder) + assert args.decoder_num_layers % num_ranks_in_decoder == 0, \ + 'decoder_num_layers (%d) must be divisible by number of ranks given to decoder (%d)' % (args.decoder_num_layers, num_ranks_in_decoder) + if parallel_state.is_pipeline_stage_before_split(): + num_layers = ( + 0 + if args.standalone_embedding_stage + and parallel_state.get_pipeline_model_parallel_rank() == 0 else + args.encoder_num_layers // num_ranks_in_encoder + ) + else: + num_layers = args.decoder_num_layers // num_ranks_in_decoder + else: + assert args.num_layers == args.encoder_num_layers + assert args.num_layers % args.transformer_pipeline_model_parallel_size == 0, \ + 'num_layers must be divisible by transformer_pipeline_model_parallel_size' + + # When a standalone embedding stage is used, all transformer layers + # are divided among pipeline rank >= 1, while on pipeline rank 0, + # ranks either contain the input embedding layer (virtual pp rank 0), + # or no layers at all (virtual pp rank >= 1). + num_layers = ( + 0 + if args.standalone_embedding_stage + and parallel_state.get_pipeline_model_parallel_rank() == 0 else + args.num_layers // args.transformer_pipeline_model_parallel_size + ) + else: + if not is_decoder: + num_layers = args.encoder_num_layers + else: + num_layers = args.decoder_num_layers + return num_layers + + +def _get_layer_type(model_type, default_layer_type, retro_layer_numbers, + layer_number): + args = get_args() + if args.retro_add_retriever and layer_number in retro_layer_numbers: + if model_type == ModelType.retro_decoder: + return LayerType.retro_decoder_with_retriever \ + if layer_number == retro_layer_numbers[0] \ + else LayerType.retro_decoder + elif model_type == ModelType.retro_encoder: + return LayerType.retro_encoder + else: + raise Exception("Unsupported model type, '%s'." % model_type) + else: + return default_layer_type + + +class ParallelTransformer(MegatronModule): + """Transformer class.""" + + def __init__(self, config, + model_type, layer_type=LayerType.encoder, + self_attn_mask_type=AttnMaskType.padding, + post_layer_norm=True, + pre_process=True, + post_process=True, + drop_path_rate=0.0, + num_experts=[1]): + super(ParallelTransformer, self).__init__() + args = get_args() + + self.layer_type = layer_type + self.model_type = model_type + self.bf16 = config.bf16 + self.fp32_residual_connection = config.fp32_residual_connection + self.post_layer_norm = post_layer_norm + self.pre_process = pre_process + self.post_process = post_process + self.input_tensor = None + self.drop_path_rate = drop_path_rate + self.transformer_impl = args.transformer_impl + self.retro_add_retriever = args.retro_add_retriever + self.ds_inference = args.ds_inference + self.device_name = get_accelerator().device_name() + + # Store activation checkpoiting flag. + self.checkpoint_activations = args.checkpoint_activations + self.checkpoint_num_layers = args.checkpoint_num_layers + self.recompute_granularity = config.recompute_granularity + self.recompute_method = config.recompute_method + self.recompute_num_layers = config.recompute_num_layers + self.distribute_saved_activations = \ + config.distribute_saved_activations and not config.sequence_parallel + + self.sequence_parallel = config.sequence_parallel + + self.use_fp8 = False + # Transformer Engine Init. + self.transformer_engine_rope_available = False + if self.transformer_impl == 'transformer_engine' and self.device_name == 'cuda': + global transformer_engine + import transformer_engine + from importlib.metadata import version + from pkg_resources import packaging + + te_version = packaging.version.Version(version("transformer-engine")) + if te_version >= packaging.version.Version("0.10.0"): + self.transformer_engine_rope_available = True + + del version, packaging + + self.use_fp8 = args.fp8_e4m3 or args.fp8_hybrid + self.fp8_recipe = None + self.fp8_group = None + if self.use_fp8: + self.fp8_group = parallel_state.get_data_parallel_group() + if args.fp8_e4m3: + fp8_format = transformer_engine.common.recipe.Format.E4M3 + elif args.fp8_hybrid: + fp8_format = transformer_engine.common.recipe.Format.HYBRID + self.fp8_recipe = transformer_engine.common.recipe.DelayedScaling( + margin=args.fp8_margin, + interval=args.fp8_interval, + fp8_format=fp8_format, + amax_history_len=args.fp8_amax_history_len, + amax_compute_algo=args.fp8_amax_compute_algo, + override_linear_precision=(False, False, not args.fp8_wgrad), + ) + + self.num_microbatches_in_previous_step = -1 + self.microbatch_count = 0 + self.checkpoint_core_attention = config.recompute_granularity == 'selective' + + # Number of layers. + self.num_layers = _get_num_layers(args, model_type, + layer_type==LayerType.decoder) + + self.drop_path_rates = [ + rate.item() for rate in + torch.linspace(0, self.drop_path_rate, config.num_layers)] + + self.retro_layer_numbers = None + if model_type == ModelType.retro_decoder: + retro_layer_start = 6 if config.num_layers <= 15 else 9 + self.retro_layer_numbers = \ + np.arange(retro_layer_start, args.num_layers + 1, 3).tolist() + if model_type == ModelType.retro_encoder: + self.retro_layer_numbers = [1] + + # Transformer layers. + if args.retro_add_retriever: + assert self.recompute_granularity != 'full', \ + "Full recompute not supported for Retro." + assert args.transformer_impl == 'local', \ + "Transformer engine does not support Retro layers." + def build_layer(layer_number, n_e): + if args.transformer_impl == 'local' or self.device_name == 'hpu': + current_layer_type = _get_layer_type( + model_type, layer_type, self.retro_layer_numbers, + layer_number) + return ParallelTransformerLayer( + config, + layer_number, + layer_type=current_layer_type, + self_attn_mask_type=self_attn_mask_type, + drop_path_rate=self.drop_path_rates[layer_number - 1], + num_experts=n_e) + else: + assert config.num_attention_heads == config.num_key_value_heads, \ + 'Transformer_engine does not support GQA' + return transformer_engine.pytorch.TransformerLayer( + config.hidden_size, + config.ffn_hidden_size, + config.num_attention_heads, + layernorm_epsilon=config.layernorm_epsilon, + hidden_dropout=config.hidden_dropout, + attention_dropout=config.attention_dropout, + init_method=config.init_method, + output_layer_init_method=config.output_layer_init_method, + layer_number=layer_number, + kv_channels=config.kv_channels, + self_attn_mask_type=self_attn_mask_type.name, + tp_group=parallel_state.get_tensor_model_parallel_group(), + get_rng_state_tracker=tensor_parallel.get_cuda_rng_tracker, + fuse_wgrad_accumulation=config.gradient_accumulation_fusion, + apply_query_key_layer_scaling=config.apply_query_key_layer_scaling, + attention_softmax_in_fp32=config.attention_softmax_in_fp32, + seq_length=args.seq_length, + micro_batch_size=args.micro_batch_size, + sequence_parallel=config.sequence_parallel, + params_dtype=config.params_dtype, + apply_residual_connection_post_layernorm=config.apply_residual_connection_post_layernorm, + output_layernorm=False, + layer_type="encoder", + drop_path_rate=self.drop_path_rates[layer_number - 1], + set_parallel_mode=True, + fuse_qkv_params=True) + + if config.virtual_pipeline_model_parallel_size is not None: + assert config.num_layers % config.virtual_pipeline_model_parallel_size == 0, \ + 'num_layers_per_stage must be divisible by ' \ + 'virtual_pipeline_model_parallel_size' + assert args.model_type != ModelType.encoder_and_decoder + # Number of layers in each model chunk is the number of layers in the stage, + # divided by the number of model chunks in a stage. + self.num_layers = self.num_layers // config.virtual_pipeline_model_parallel_size + # With 8 layers, 2 stages, and 4 model chunks, we want an assignment of + # layers to stages like (each list is a model chunk): + # Stage 0: [0] [2] [4] [6] + # Stage 1: [1] [3] [5] [7] + # With 8 layers, 2 stages, and 2 virtual stages, we want an assignment of + # layers to stages like (each list is a model chunk): + # Stage 0: [0, 1] [4, 5] + # Stage 1: [2, 3] [6, 7] + offset = parallel_state.get_virtual_pipeline_model_parallel_rank() * ( + config.num_layers // config.virtual_pipeline_model_parallel_size) + \ + (parallel_state.get_pipeline_model_parallel_rank() * self.num_layers) + else: + # Each stage gets a contiguous set of layers. + if args.model_type == ModelType.encoder_and_decoder and \ + parallel_state.get_pipeline_model_parallel_world_size() > 1: + pipeline_rank = parallel_state.get_pipeline_model_parallel_rank() + if layer_type == LayerType.encoder: + offset = pipeline_rank * self.num_layers + else: + num_ranks_in_enc = args.pipeline_model_parallel_split_rank + offset = (pipeline_rank - num_ranks_in_enc) * self.num_layers + else: + offset = parallel_state.get_pipeline_model_parallel_rank() * self.num_layers + + if self.num_layers == 0: + # When a standalone embedding stage is used (e.g., + # args.standalone_embedding_stage == True), virtual pipeline ranks + # on pipeline rank 0 will have zero transformer layers assigned to + # them. This results in the model's input and output tensors to be + # the same, which will cause failure for certain output tensor + # optimizations (e.g., pipeline output deallocation). To remedy + # this, we assign a 'no-op' layer on these ranks, which will + # disconnect the input tensor from the output tensor. + self.num_layers = 1 + self.layers = torch.nn.ModuleList([ NoopTransformerLayer(1) ]) + else: + assert len(num_experts) == 1 or len(num_experts) == args.num_layers // args.expert_interval, \ + 'num_experts must be either a single value or a list of the same length as the number of MoE layers' + + # Create the list of MoE experts + if len(num_experts) == 1: + num_experts = num_experts * (args.num_layers // args.expert_interval) + + # Build the layers + self.layers = [] + for i in range(self.num_layers): + layer_num = i + 1 + offset + if layer_num % args.expert_interval == 0: + n_e = num_experts[(layer_num-1) // args.expert_interval] + else: + n_e = 1 + self.layers.append(build_layer(layer_num, n_e)) + self.layers = torch.nn.ModuleList(self.layers) + + # Update dropout rate for Retro encoder. + if model_type == ModelType.retro_encoder: + for layer in self.layers: + if layer.self_attention.use_flash_attn: + layer.self_attention.core_attention_flash.dropout_p = \ + torch.nn.Dropout(args.retro_encoder_attention_dropout) + else: + layer.self_attention.core_attention.attention_dropout.p =\ + args.retro_encoder_attention_dropout + layer.hidden_dropout = args.retro_encoder_hidden_dropout + + if self.post_process and self.post_layer_norm: + # Final layer norm before output. + if args.normalization == 'layernorm': + if get_accelerator().device_name() in ['cuda', 'hpu']: + self.final_layernorm = LayerNorm( + config.hidden_size, + eps=config.layernorm_epsilon, + no_persist_layer_norm=args.no_persist_layer_norm, + sequence_parallel=config.sequence_parallel, + apply_layernorm_1p=args.apply_layernorm_1p, + mem_efficient_ln=args.mem_efficient_ln) + else: + self.final_layernorm = LayerNorm( + config.hidden_size, + eps=config.layernorm_epsilon) + else: + self.final_layernorm = MixedFusedRMSNorm(config.hidden_size, + config.layernorm_epsilon, + sequence_parallel=config.sequence_parallel) + + def _get_layer(self, layer_number): + return self.layers[layer_number] + + def _checkpointed_forward(self, hidden_states, attention_mask, + encoder_output, enc_dec_attn_mask, + rotary_pos_emb, is_first_microbatch): + args = get_args() + + """Forward method with activation checkpointing.""" + def custom(start, end): + def custom_forward(*args, **kwargs): + x_, *args = args + moe_losses = [] + for index in range(start, end): + layer = self._get_layer(index) + output = layer(x_, *args, **kwargs) + if isinstance(output, tuple): + x_, moe_loss = output + else: + x_ = output + moe_loss = torch.tensor(0.0, device=x_.device, dtype=x_.dtype, requires_grad=True) + moe_losses.append(moe_loss) + return (x_, *moe_losses) + return custom_forward + + if args.deepspeed and args.deepspeed_activation_checkpointing: + moe_losses = [] + # Make sure memory is freed. + tensor_parallel.reset_checkpointed_activations_memory_buffer() + l = 0 + while l < self.num_layers: + hidden_states, *local_moe_losses = tensor_parallel.checkpoint( + custom(l, l + self.checkpoint_num_layers), False, + hidden_states, attention_mask, encoder_output, enc_dec_attn_mask, + None, None, None, None, rotary_pos_emb) + moe_losses.extend(local_moe_losses) + l += self.checkpoint_num_layers + + return hidden_states, moe_losses + else: + moe_losses = [] + te_forward_kwargs = {} + if self.transformer_impl == 'transformer_engine': + te_forward_kwargs['is_first_microbatch'] = is_first_microbatch + if self.transformer_engine_rope_available: + te_forward_kwargs['rotary_pos_emb'] = rotary_pos_emb + + if self.recompute_method == 'uniform': + # Uniformly divide the total number of Transformer layers and + # checkpoint the input activation of each divided chunk. + # A method to further reduce memory usage reducing checkpoints. + l = 0 + while l < self.num_layers: + if self.transformer_impl == 'transformer_engine': + hidden_states, *local_moe_losses = transformer_engine.pytorch.distributed.checkpoint( + custom(l, l + self.recompute_num_layers), + self.distribute_saved_activations, + tensor_parallel.get_cuda_rng_tracker, + mpu.get_tensor_model_parallel_group(), + hidden_states, attention_mask, encoder_output, + enc_dec_attn_mask, **te_forward_kwargs) + else: + hidden_states, *local_moe_losses = tensor_parallel.checkpoint( + custom(l, l + self.recompute_num_layers), + self.distribute_saved_activations, + hidden_states, attention_mask, + encoder_output, enc_dec_attn_mask, + None, None, None, None, rotary_pos_emb) + moe_losses.extend(local_moe_losses) + l += self.recompute_num_layers + elif self.recompute_method == 'block': + # Checkpoint the input activation of only a set number of individual + # Transformer layers and skip the rest. + # A method fully use the device memory removing redundant re-computation. + for l in range(self.num_layers): + if l < self.recompute_num_layers: + if self.transformer_impl == 'transformer_engine': + hidden_states, *local_moe_losses = transformer_engine.pytorch.distributed.checkpoint( + custom(l, l + 1), + self.distribute_saved_activations, + tensor_parallel.get_cuda_rng_tracker, + mpu.get_tensor_model_parallel_group(), + hidden_states, attention_mask, encoder_output, + enc_dec_attn_mask, **te_forward_kwargs) + else: + hidden_states, *local_moe_losses = tensor_parallel.checkpoint( + custom(l, l + 1), + self.distribute_saved_activations, + hidden_states, attention_mask, + encoder_output, enc_dec_attn_mask, + None, None, None, None, rotary_pos_emb) + else: + if self.transformer_impl == 'transformer_engine': + hidden_states, *local_moe_losses = custom(l, l + 1)( + hidden_states, attention_mask, encoder_output, + enc_dec_attn_mask, **te_forward_kwargs) + else: + hidden_states, *local_moe_losses = custom(l, l + 1)( + hidden_states, attention_mask, + encoder_output, enc_dec_attn_mask, + None, None, None, None, rotary_pos_emb) + + moe_losses.extend(local_moe_losses) + else: + raise ValueError("Invalid activation recompute method.") + return hidden_states, moe_losses + + def set_input_tensor(self, input_tensor): + """Set input tensor to be used instead of forward()'s input. + + When doing pipeline parallelism the input from the previous + stage comes from communication, not from the input, so the + model's forward_step_func won't have it. This function is thus + used by internal code to bypass the input provided by the + forward_step_func""" + self.input_tensor = input_tensor + + def forward(self, hidden_states, attention_mask, + encoder_output=None, enc_dec_attn_mask=None, + retriever_input=None, + retriever_output=None, + retriever_attn_mask=None, + inference_params=None, + rotary_pos_emb=None): + # hidden_states: [s, b, h] + + # Checks. + if inference_params: + assert self.recompute_granularity is None, \ + 'inference does not work with activation checkpointing' + + # TODO: Below old DeepSpeed code are commented because it's unsure whether + # it is still relevant. + # # Reza's note: DeepSpeed inference does not support transposes + # if not self.ds_inference: + # if self.pre_process: + # # Data format change to avoid explicit tranposes : [b s h] --> [s b h]. + # # If the input flag for fp32 residual connection is set, convert for float. + # if self.fp32_residual_connection: + # hidden_states = hidden_states.transpose(0, 1).contiguous().float() + # # Otherwise, leave it as is. + # else: + # hidden_states = hidden_states.transpose(0, 1).contiguous() + # else: + # # See set_input_tensor() + # hidden_states = self.input_tensor + # if encoder_output is not None: + # encoder_output = encoder_output.transpose(0, 1).contiguous() + + if not self.pre_process: + # See set_input_tensor() + hidden_states = self.input_tensor + + # Viewless tensor. + # - We only need to create a viewless tensor in the case of micro batch + # size (mbs) == 1, since in this case, 'hidden_states.transpose()' + # above creates a view tensor, and '.contiguous()' is a pass-through. + # For mbs >= 2, '.contiguous()' creates a new tensor, eliminating + # the need to make it viewless. + # + # However, we don't explicitly check mbs == 1 here because + # make_viewless_tensor() has negligible overhead when its input + # is already viewless. + # + # - For the 'else' case above, calling make_viewless_tensor() here is + # likely redundant, since p2p_communication.py (likely originator) + # already creates viewless tensors. That said, make_viewless_tensor() + # is called here to be future-proof and corner-case-proof. + hidden_states = core.utils.make_viewless_tensor( + hidden_states, + requires_grad=True, + keep_graph=True, + ) + + # RNG context. + if self.sequence_parallel: + rng_context = tensor_parallel.get_cuda_rng_tracker().fork() + else: + rng_context = nullcontext() + + # Forward layers. + with rng_context: + # The fp8_autocast context manager is a no-op when enabled=True + # The if...else serves to short circuit name resolution for fp8_autocast + with transformer_engine.pytorch.fp8_autocast( + enabled=self.use_fp8, + fp8_recipe=self.fp8_recipe, + fp8_group=self.fp8_group + ) if self.use_fp8 else nullcontext(): + # Determine if the current iteration is first microbatch + if self.num_microbatches_in_previous_step != get_num_microbatches(): + self.microbatch_count = 0 # Reset count on new batch size rampup interval + self.num_microbatches_in_previous_step = get_num_microbatches() + is_first_microbatch = self.microbatch_count % get_num_microbatches() == 0 + + # Forward pass. + moe_losses = [] + if self.checkpoint_activations: + hidden_states, moe_losses = self._checkpointed_forward(hidden_states, + attention_mask, + encoder_output, + enc_dec_attn_mask, + rotary_pos_emb, + is_first_microbatch) + elif self.recompute_granularity == 'full': + hidden_states, moe_losses = self._checkpointed_forward(hidden_states, + attention_mask, + encoder_output, + enc_dec_attn_mask, + rotary_pos_emb, + is_first_microbatch) + else: + forward_kwargs = { + 'encoder_output': encoder_output, + 'enc_dec_attn_mask': enc_dec_attn_mask, + 'inference_params': inference_params, + } + + if self.transformer_impl == 'transformer_engine': + forward_kwargs['is_first_microbatch'] = is_first_microbatch + forward_kwargs['checkpoint_core_attention'] = self.checkpoint_core_attention + if self.transformer_engine_rope_available: + forward_kwargs['rotary_pos_emb'] = rotary_pos_emb + else: + forward_kwargs['rotary_pos_emb'] = rotary_pos_emb + forward_kwargs['retriever_input'] = retriever_input + forward_kwargs['retriever_output'] = retriever_output + forward_kwargs['retriever_attn_mask'] = retriever_attn_mask + + for index in range(self.num_layers): + layer = self._get_layer(index) + + hidden_states = layer( + hidden_states, + attention_mask, + **forward_kwargs) + + # First Retro decoder layer returns both hidden_states + # and retriever_output. Make retriever_output available + # to subsequence Retro layers. + if isinstance(hidden_states, tuple): + assert (len(hidden_states) == 2 or len(hidden_states) == 3) + if len(hidden_states) == 2: + if not self.ds_inference: + hidden_states, moe_loss = hidden_states + moe_losses.append(moe_loss) + else: + forward_kwargs["retriever_output"] = hidden_states[1] + if not self.ds_inference: + hidden_states, _, moe_loss = hidden_states + moe_losses.append(moe_loss) + + # Skip counter update for eval and activation checkpointing + if torch.is_grad_enabled() and self.training: + self.microbatch_count += 1 + + # Final layer norm. + if self.post_process and self.post_layer_norm: + # TODO: Below old DeepSpeed code are commented because it's unsure whether + # it is still relevant. + # if not self.ds_inference: + # # Reverting data format change [s b h] --> [b s h]. + # hidden_states = hidden_states.transpose(0, 1).contiguous() + hidden_states = self.final_layernorm(hidden_states) + + return (hidden_states, *moe_losses) + +class LMHeadPipe(MegatronModule): + """ + Arguments: + vocab_size: size of vocabulary. + hidden_size: hidden size + gather_output: wether output logits being gathered or not. + init_method: init method for weight initialization + config: + """ + + def __init__(self, hidden_size, vocab_size, config): + args = get_args() + super(LMHeadPipe, self).__init__() + self.lm_head = tensor_parallel.ColumnParallelLinear(input_size=hidden_size, + output_size=vocab_size, + bias=False, + config=config, + init_method=config.init_method,) + + def forward(self, inputs, **kwargs): + assert torch.is_tensor(inputs) or isinstance(inputs, tuple) + if isinstance(inputs, tuple): + hidden_states = inputs[0] + else: + hidden_states = inputs + + if not hasattr(self, '_args'): + self._args = get_args() + + if hasattr(self._args, 'attn_mask'): + attention_mask = None + else: + attention_mask = inputs[1] + + logits, _ = self.lm_head(hidden_states) + + # If cmd args has attn_mask, we don't forward it as an activation. + if hasattr(self._args, 'attn_mask'): + return logits + else: + return logits, attention_mask diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/utils.py b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e08a0ada367a54f425b268851a6614f684ddbc2f --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/utils.py @@ -0,0 +1,83 @@ +# Copyright (C) 2024 Habana Labs, Ltd. an Intel Company. +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. + +"""Utilities for models.""" + +import math + +import torch + +from megatron import get_args + +from deepspeed.runtime.zero import GatheredParameters +from deepspeed.accelerator import get_accelerator + +def init_method_normal(sigma): + """Init method based on N(0, sigma).""" + def init_(tensor): + return torch.nn.init.normal_(tensor, mean=0.0, std=sigma) + + return init_ + + +def scaled_init_method_normal(sigma, num_layers): + """Init method based on N(0, sigma/sqrt(2*num_layers).""" + std = sigma / math.sqrt(2.0 * num_layers) + + def init_(tensor): + return torch.nn.init.normal_(tensor, mean=0.0, std=std) + + return init_ + + +def gather_and_init(param, init_method): + with GatheredParameters(param, modifier_rank=0): + init_method(param) + + +def perform_masking(attention_scores, attention_mask): + if attention_mask.dtype == torch.bool: + attention_scores.masked_fill_(attention_mask, -10000.0) + else: + attention_scores.add_(attention_mask) + + +def attention_mask_func(attention_scores, attention_mask): + args = get_args() + if args.curriculum_learning_legacy or args.data_efficiency_curriculum_learning: + attention_mask_ = attention_mask + actual_seqlen = attention_scores.size()[2] + if actual_seqlen != attention_mask_.size()[2]: + # attention_mask has size [1, 1, seqlen, seqlen] + attention_mask_ = attention_mask_[:, :, :actual_seqlen, :actual_seqlen].contiguous() + perform_masking(attention_scores, attention_mask_) + else: + perform_masking(attention_scores, attention_mask) + return attention_scores + + +def get_linear_layer(rows, columns, init_method, gather_params_on_init=False): + """Simple linear layer with weight initialization.""" + layer = torch.nn.Linear(rows, columns, + device=get_accelerator().current_device_name(), + dtype=get_args().params_dtype) + if get_args().perform_initialization: + with GatheredParameters(layer.weight, modifier_rank=0, enabled=gather_params_on_init): + init_method(layer.weight) + with torch.no_grad(): + with GatheredParameters(layer.bias, modifier_rank=0, enabled=gather_params_on_init): + layer.bias.zero_() + return layer + +@torch.jit.script +def gelu_impl(x): + """OpenAI's gelu implementation.""" + return 0.5 * x * (1.0 + torch.tanh(0.7978845608028654 * x * + (1.0 + 0.044715 * x * x))) +def openai_gelu(x): + return gelu_impl(x) + +#This is actually Python equivalent of torch.nn.functional.gelu(), also with type hints for ONNX exporter +@torch.jit.script +def erf_gelu(x): + return x * 0.5 * (torch.erf(x / 1.41421).to(dtype=x.dtype)+torch.ones_like(x).to(dtype=x.dtype)) diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/__init__.py b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/__pycache__/__init__.cpython-310.pyc b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82721cea4bb0a415e663062a21d1d228b3d774e7 Binary files /dev/null and b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/__pycache__/__init__.cpython-310.pyc differ diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/__pycache__/knn_monitor.cpython-310.pyc b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/__pycache__/knn_monitor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59881452383f1fcf151d7a3ab26459ab3af96f0c Binary files /dev/null and b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/__pycache__/knn_monitor.cpython-310.pyc differ diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/classification.py b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/classification.py new file mode 100644 index 0000000000000000000000000000000000000000..2be1951eeade7412f8a29abe420e92d9e54a220e --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/classification.py @@ -0,0 +1,86 @@ +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. + +"""Vision Transformer(VIT) model.""" + +import torch +from torch.nn.init import trunc_normal_ +from megatron import get_args +from megatron.model.utils import get_linear_layer +from megatron.model.vision.vit_backbone import VitBackbone, VitMlpHead +from megatron.model.vision.mit_backbone import mit_b3_avg +from megatron.model.module import MegatronModule + +class VitClassificationModel(MegatronModule): + """Vision Transformer Model.""" + + def __init__(self, config, num_classes, finetune=False, + pre_process=True, post_process=True): + super(VitClassificationModel, self).__init__() + args = get_args() + + self.hidden_size = args.hidden_size + self.num_classes = num_classes + self.finetune = finetune + self.pre_process = pre_process + self.post_process = post_process + self.backbone = VitBackbone( + config=config, + pre_process=self.pre_process, + post_process=self.post_process, + single_token_output=True + ) + + if self.post_process: + if not self.finetune: + self.head = VitMlpHead(self.hidden_size, self.num_classes) + else: + self.head = get_linear_layer( + self.hidden_size, + self.num_classes, + torch.nn.init.zeros_, + gather_params_on_init=args.zero_stage == 3 + ) + + def set_input_tensor(self, input_tensor): + """See megatron.model.transformer.set_input_tensor()""" + self.backbone.set_input_tensor(input_tensor) + + def forward(self, input): + hidden_states = self.backbone(input) + + if self.post_process: + hidden_states = self.head(hidden_states) + + return hidden_states + + +class MitClassificationModel(MegatronModule): + """Mix vision Transformer Model.""" + + def __init__(self, num_classes, + pre_process=True, post_process=True): + super(MitClassificationModel, self).__init__() + args = get_args() + + self.hidden_size = args.hidden_size + self.num_classes = num_classes + + self.backbone = mit_b3_avg() + self.head = torch.nn.Linear(512, num_classes) + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, torch.nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, torch.nn.Linear) and m.bias is not None: + torch.nn.init.constant_(m.bias, 0) + + def set_input_tensor(self, input_tensor): + """See megatron.model.transformer.set_input_tensor()""" + pass + + def forward(self, input): + hidden_states = self.backbone(input) + hidden_states = self.head(hidden_states) + + return hidden_states diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/dino.py b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/dino.py new file mode 100644 index 0000000000000000000000000000000000000000..1c577d2e199246e0687e3510312ccfdf0ea1b300 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/dino.py @@ -0,0 +1,290 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# +# This source code is licensed under the Apache license found in the +# LICENSE file in the root directory of this source tree. + +# copied from https://github.com/facebookresearch/dino/blob/main/main_dino.py +# reworked/refactored some parts to make it run in Megatron. +import math +import apex +import einops +import torch +import numpy as np +import torch.nn.functional as F +from torch.nn.init import trunc_normal_ +from megatron import get_args, print_rank_0 +from megatron.model.utils import get_linear_layer +from megatron.model.vision.vit_backbone import VitBackbone +from megatron.model.module import MegatronModule +from megatron.model.vision.mit_backbone import mit_b5_avg +from megatron.model.vision.esvit_swin_backbone import get_swin + + +class DINOLoss(torch.nn.Module): + def __init__(self, out_dim, ncrops, warmup_teacher_temp, teacher_temp, + warmup_teacher_temp_epochs, nepochs, student_temp=0.1, + center_momentum=0.9): + super().__init__() + self.student_temp = student_temp + self.center_momentum = center_momentum + self.ncrops = ncrops + self.register_buffer("center", torch.zeros(1, out_dim)) + # we apply a warm up for the teacher temperature because + # a too high temperature makes the training instable at the beginning + self.teacher_temp_schedule = np.concatenate(( + np.linspace(warmup_teacher_temp, + teacher_temp, warmup_teacher_temp_epochs), + np.ones(nepochs - warmup_teacher_temp_epochs) * teacher_temp + )) + self.teacher_temp = teacher_temp + + def forward(self, student_output, teacher_output, iteration): + """ + Cross-entropy between softmax outputs of the teacher + and student network. + """ + args = get_args() + student_out = student_output / self.student_temp + student_out = student_out.chunk(self.ncrops) + + epoch = iteration // args.iter_per_epoch + + # teacher centering and sharpening + temp = self.teacher_temp_schedule[epoch] + teacher_out = F.softmax((teacher_output - self.center) / temp, dim=-1) + + teacher_out = teacher_out.detach().chunk(2) + + total_loss = 0 + n_loss_terms = 0 + for iq, q in enumerate(teacher_out): + for v in range(len(student_out)): + if v == iq: + # we skip cases where student and teacher operate on the same view + continue + loss = torch.sum(-q * F.log_softmax(student_out[v], dim=-1), dim=-1) + total_loss += loss.mean() + n_loss_terms += 1 + total_loss /= n_loss_terms + self.update_center(teacher_output) + return total_loss + + @torch.no_grad() + def update_center(self, teacher_output): + """ + Update center used for teacher output. + """ + batch_center = torch.sum(teacher_output, dim=0, keepdim=True) + torch.distributed.all_reduce(batch_center) + batch_center = batch_center / (len(teacher_output) * torch.distributed.get_world_size()) + self.center = self.center * self.center_momentum + batch_center * (1 - self.center_momentum) + +class DINOHead(torch.nn.Module): + def __init__(self, in_dim, out_dim, norm_last_layer=True, nlayers=3): + super().__init__() + args = get_args() + hidden_dim = args.dino_head_hidden_size + bottleneck_dim = args.dino_bottleneck_size + nlayers = max(nlayers, 1) + if nlayers == 1: + self.mlp = torch.nn.Linear(in_dim, bottleneck_dim) + else: + layers = [torch.nn.Linear(in_dim, hidden_dim)] + layers.append(torch.nn.GELU()) + for _ in range(nlayers - 2): + layers.append(torch.nn.Linear(hidden_dim, hidden_dim)) + layers.append(torch.nn.GELU()) + layers.append(torch.nn.Linear(hidden_dim, bottleneck_dim)) + self.mlp = torch.nn.Sequential(*layers) + self.apply(self._init_weights) + self.last_layer = torch.nn.utils.weight_norm(torch.nn.Linear(bottleneck_dim, out_dim, bias=False)) + self.last_layer.weight_g.data.fill_(1) + if norm_last_layer: + self.last_layer.weight_g.requires_grad = False + + def _init_weights(self, m): + if isinstance(m, torch.nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, torch.nn.Linear) and m.bias is not None: + torch.nn.init.constant_(m.bias, 0) + + def forward(self, x): + x = self.mlp(x) + x = torch.nn.functional.normalize(x, dim=-1, p=2) + x = self.last_layer(x) + return x + + +class MultiCropWrapper(MegatronModule): + + """ + Perform forward pass separately on each resolution input. + The inputs corresponding to a single resolution are clubbed and single + forward is run on the same resolution inputs. Hence we do several + forward passes = number of different resolutions used. We then + concatenate all the output features and run the head forward on these + concatenated features. + """ + def __init__(self, backbone, head): + super(MultiCropWrapper, self).__init__() + # disable layers dedicated to ImageNet labels classification + #backbone.fc, backbone.head = torch.nn.Identity(), torch.nn.Identity() + self.backbone = backbone + self.head = head + + def forward(self, x): + # convert to list + if not isinstance(x, list): + x = [x] + idx_crops = torch.cumsum(torch.unique_consecutive( + torch.tensor([inp.shape[-1] for inp in x]), + return_counts=True, + )[1], 0) + + start_idx = 0 + for end_idx in idx_crops: + _out = self.backbone(torch.cat(x[start_idx: end_idx])) + if start_idx == 0: + output = _out + else: + output = torch.cat((output, _out)) + start_idx = end_idx + # Run the head forward on the concatenated features. + if self.training: + return self.head(output) + else: + return output + + +def cosine_scheduler(base_value, final_value, epochs, niter_per_ep, + warmup_epochs=0, start_warmup_value=0): + warmup_schedule = np.array([]) + warmup_iters = warmup_epochs * niter_per_ep + if warmup_epochs > 0: + warmup_schedule = \ + np.linspace(start_warmup_value, base_value, warmup_iters) + + iters = np.arange(epochs * niter_per_ep - warmup_iters) + schedule = final_value + 0.5 * (base_value - final_value) \ + * (1 + np.cos(np.pi * iters / len(iters))) + + schedule = np.concatenate((warmup_schedule, schedule)) + assert len(schedule) == epochs * niter_per_ep + return schedule + + +def get_student_backbone_and_num_features(config, pre_process=True, post_process=True): + args = get_args() + + if args.vision_backbone_type == 'vit': + student = VitBackbone(config, + pre_process=pre_process, + post_process=post_process, + drop_path_rate=0.1, + single_token_output=True) + num_features = args.hidden_size + elif args.vision_backbone_type == 'mit': + student = mit_b5_avg(drop_path_rate=0.1) + num_features = 512 + elif args.vision_backbone_type == 'swin': + student = get_swin() + num_features = student.num_features + else: + raise Exception('{} vision backbone is not supported.'.format( + args.vision_backbone_type)) + + return student, num_features + +def get_teacher_backbone_and_num_features(config, pre_process=True, post_process=True): + args = get_args() + + if args.vision_backbone_type == 'vit': + teacher = VitBackbone(config, + pre_process=pre_process, + post_process=post_process, + single_token_output=True) + num_features = args.hidden_size + elif args.vision_backbone_type == 'mit': + teacher = mit_b5_avg(drop_path_rate=0.0) + num_features = 512 + elif args.vision_backbone_type == 'swin': + teacher = get_swin(is_teacher=True) + num_features = teacher.num_features + else: + raise Exception('{} vision backbone is not supported.'.format( + args.vision_backbone_type)) + return teacher, num_features + + +class DINOPretrainModel(MegatronModule): + def __init__(self, config, pre_process=True, post_process=True): + super(DINOPretrainModel, self).__init__() + args = get_args() + self.out_dim = 65536 + + self.dino_loss = DINOLoss( + self.out_dim, + args.dino_local_crops_number + 2, + args.dino_warmup_teacher_temp, + args.dino_teacher_temp, + args.dino_warmup_teacher_temp_epochs, + 300, + ) + + self.pre_process = pre_process + self.post_process = post_process + self.momentum_teacher = 0.996 + + student_backbone, num_features = \ + get_student_backbone_and_num_features(config, pre_process, post_process) + + self.student = MultiCropWrapper( + student_backbone, + DINOHead(num_features, self.out_dim, + norm_last_layer=args.dino_norm_last_layer) + ) + + self.momentum_schedule = cosine_scheduler( + self.momentum_teacher, 1, + args.train_iters // args.iter_per_epoch, + args.iter_per_epoch + ) + + teacher_backbone, num_features = \ + get_teacher_backbone_and_num_features(config, pre_process, post_process) + self.teacher = MultiCropWrapper( + teacher_backbone, + DINOHead(num_features, self.out_dim) + ) + self.teacher.load_state_dict(self.student.state_dict()) + + for p in self.teacher.parameters(): + if hasattr(p, "requires_grad") and p.requires_grad is not None: + p.requires_grad = False + + def set_input_tensor(self, tensor): + pass + + def forward(self, input): + student_output = None + if self.training: + student_output = self.student(input) + teacher_output = self.teacher(input[:2]) + else: + teacher_output = self.teacher(input) + return student_output, teacher_output + + def cancel_gradients_last_layer(self, iteration): + args = get_args() + epoch = iteration // args.iter_per_epoch + if epoch < args.dino_freeze_last_layer: + for n, p in self.student.named_parameters(): + if "last_layer" in n: + p.grad = None + + def update_momentum(self, iteration): + with torch.no_grad(): + m = self.momentum_schedule[iteration] + for param_q, param_k in zip(self.student.parameters(), self.teacher.parameters()): + param_k.data.mul_(m).add_((1 - m) * param_q.detach().data) + diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/esvit_swin_backbone.py b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/esvit_swin_backbone.py new file mode 100644 index 0000000000000000000000000000000000000000..70aee3db429bf63680b7c19b4d5acfe25ee2edf5 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/esvit_swin_backbone.py @@ -0,0 +1,849 @@ +# Copyright (c) 2021 Microsoft +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. +# -------------------------------------------------------- +# Modified by Chunyuan Li (chunyl@microsoft.com) +# Swin Transformer +# -------------------------------------------------------- + +import os +import logging +import torch +import torch.nn as nn +import torch.nn.functional as F +from functools import partial +import torch.distributed as dist +from torch.nn.init import trunc_normal_ +from megatron.model.transformer import DropPath +from megatron import get_args +from megatron.model import LayerNorm +import numpy as np +from math import sqrt + + +class Mlp(nn.Module): + def __init__(self, in_features, hidden_features=None, + out_features=None, act_layer=nn.GELU, drop=0.): + super(Mlp, self).__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +def window_partition(x, window_size): + """ + Args: + x: (B, H, W, C) + window_size (int): window size + Returns: + windows: (num_windows*B, window_size, window_size, C) + """ + B, H, W, C = x.shape + x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) + windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + return windows + + +def window_reverse(windows, window_size, H, W): + """ + Args: + windows: (num_windows*B, window_size, window_size, C) + window_size (int): Window size + H (int): Height of image + W (int): Width of image + Returns: + x: (B, H, W, C) + """ + B = int(windows.shape[0] / (H * W / window_size / window_size)) + x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) + return x + + +class WindowAttention(nn.Module): + r"""Window based multi-head self attention (W-MSA) module with relative position bias. + It supports both of shifted and non-shifted window. + Args: + dim (int): Number of input channels. + window_size (tuple[int]): The height and width of the window. + num_heads (int): Number of attention heads. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set + attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 + proj_drop (float, optional): Dropout ratio of output. Default: 0.0 + """ + + def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.): + + super(WindowAttention, self).__init__() + self.dim = dim + self.window_size = window_size # Wh, Ww + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = qk_scale or head_dim ** -0.5 + + # define a parameter table of relative position bias + self.relative_position_bias_table = nn.Parameter( + torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH + + # get pair-wise relative position index for each token inside the window + coords_h = torch.arange(self.window_size[0]) + coords_w = torch.arange(self.window_size[1]) + coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww + coords_flatten = torch.flatten(coords, 1) # 2 Wh*Ww + relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww + relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 + relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 + relative_coords[:, :, 1] += self.window_size[1] - 1 + relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 + relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww + self.register_buffer("relative_position_index", relative_position_index) + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + + trunc_normal_(self.relative_position_bias_table, std=.02) + self.softmax = nn.Softmax(dim=-1) + + def forward(self, x, mask=None): + """ + Args: + x: input features with shape of (num_windows*B, N, C) + mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None + """ + B_, N, C = x.shape + qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) + q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) + + q = q * self.scale + attn = (q @ k.transpose(-2, -1)) + + relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view( + self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH + relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww + attn = attn + relative_position_bias.unsqueeze(0) + + if mask is not None: + nW = mask.shape[0] + attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0).type(attn.type()) + attn = attn.view(-1, self.num_heads, N, N) + attn = self.softmax(attn) + else: + attn = self.softmax(attn) + + attn_out = attn + attn = self.attn_drop(attn) + + x = (attn @ v).transpose(1, 2).reshape(B_, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x, attn_out + + def extra_repr(self) -> str: + return f'dim={self.dim}, window_size={self.window_size}, num_heads={self.num_heads}' + + def flops(self, N): + # calculate flops for 1 window with token length of N + flops = 0 + # qkv = self.qkv(x) + flops += N * self.dim * 3 * self.dim + # attn = (q @ k.transpose(-2, -1)) + flops += self.num_heads * N * (self.dim // self.num_heads) * N + # x = (attn @ v) + flops += self.num_heads * N * N * (self.dim // self.num_heads) + # x = self.proj(x) + flops += N * self.dim * self.dim + return flops + + @staticmethod + def compute_macs(module, input, output): + B, N, C = input[0].shape + + module.__flops__ += module.flops(N) * B + + +class SwinTransformerBlock(nn.Module): + r"""Swin Transformer Block. + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resulotion. + num_heads (int): Number of attention heads. + window_size (int): Window size. + shift_size (int): Shift size for SW-MSA. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float, optional): Stochastic depth rate. Default: 0.0 + act_layer (nn.Module, optional): Activation layer. Default: nn.GELU + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + """ + + def __init__(self, dim, input_resolution, num_heads, window_size=7, shift_size=0, + mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0., + act_layer=nn.GELU, norm_layer=nn.LayerNorm): + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.num_heads = num_heads + self.window_size = window_size + self.shift_size = shift_size + self.mlp_ratio = mlp_ratio + if min(self.input_resolution) <= self.window_size: + # if window size is larger than input resolution, we don't partition windows + self.shift_size = 0 + self.window_size = min(self.input_resolution) + assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size" + + self.norm1 = norm_layer(dim) + self.attn = WindowAttention( + dim, window_size=(self.window_size, self.window_size), num_heads=num_heads, + qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) + + self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) + + self.H = input_resolution[0] + self.W = input_resolution[1] + + self.attn_mask_dict = {} + + + def create_attn_mask(self, H, W): + # calculate attention mask for SW-MSA + + Hp = int(np.ceil(H / self.window_size)) * self.window_size + Wp = int(np.ceil(W / self.window_size)) * self.window_size + img_mask = torch.zeros((1, Hp, Wp, 1)) # 1 Hp Wp 1 + h_slices = (slice(0, -self.window_size), + slice(-self.window_size, -self.shift_size), + slice(-self.shift_size, None)) + w_slices = (slice(0, -self.window_size), + slice(-self.window_size, -self.shift_size), + slice(-self.shift_size, None)) + cnt = 0 + for h in h_slices: + for w in w_slices: + img_mask[:, h, w, :] = cnt + cnt += 1 + + mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1 + mask_windows = mask_windows.view(-1, self.window_size * self.window_size) + attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) + attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) + + return attn_mask + + + def forward(self, x): + B, L, C = x.shape + H = int(sqrt(L)) + W = H + + shortcut = x + x = self.norm1(x) + x = x.view(B, H, W, C) + + # pad feature maps to multiples of window size + pad_l = pad_t = 0 + pad_r = (self.window_size - W % self.window_size) % self.window_size + pad_b = (self.window_size - H % self.window_size) % self.window_size + x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b)) + _, Hp, Wp, _ = x.shape + + # cyclic shift + if self.shift_size > 0: + shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) + + if H in self.attn_mask_dict.keys(): + attn_mask = self.attn_mask_dict[H] + else: + self.attn_mask_dict[H] = self.create_attn_mask(self.H, self.W).to(x.device) + attn_mask = self.attn_mask_dict[H] + + else: + shifted_x = x + attn_mask = None + + # partition windows + x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C + x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C + + # W-MSA/SW-MSA + attn_windows, attn = self.attn(x_windows, attn_mask) # nW*B, window_size*window_size, C + + # merge windows + attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) + shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C + + # reverse cyclic shift + if self.shift_size > 0: + x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) + else: + x = shifted_x + + if pad_r > 0 or pad_b > 0: + x = x[:, :H, :W, :].contiguous() + + x = x.view(B, H * W, C) + + # FFN + x = shortcut + self.drop_path(x) + x = x + self.drop_path(self.mlp(self.norm2(x))) + + return x, attn + + def extra_repr(self) -> str: + return f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " \ + f"window_size={self.window_size}, shift_size={self.shift_size} mlp_ratio={self.mlp_ratio}" + + def flops(self): + flops = 0 + H, W = self.input_resolution + # norm1 + flops += self.dim * H * W + # W-MSA/SW-MSA + nW = H * W / self.window_size / self.window_size + flops += nW * self.attn.flops(self.window_size * self.window_size) + # mlp + flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio + # norm2 + flops += self.dim * H * W + return flops + + +class PatchMerging(nn.Module): + r"""Patch Merging Layer. + Args: + input_resolution (tuple[int]): Resolution of input feature. + dim (int): Number of input channels. + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + """ + + def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm): + super().__init__() + self.input_resolution = input_resolution + self.dim = dim + self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) + self.norm = norm_layer(4 * dim) + + def forward(self, x): + """ Forward function. + Args: + x: Input feature, tensor size (B, H*W, C). + H, W: Spatial resolution of the input feature. + """ + B, L, C = x.shape + H = int(sqrt(L)) + W = H + + x = x.view(B, H, W, C) + + # padding + pad_input = (H % 2 == 1) or (W % 2 == 1) + if pad_input: + x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2)) + + x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C + x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C + x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C + x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C + x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C + x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C + + x = self.norm(x) + x = self.reduction(x) + + return x + + + def extra_repr(self) -> str: + return f"input_resolution={self.input_resolution}, dim={self.dim}" + + def flops(self): + H, W = self.input_resolution + flops = H * W * self.dim + flops += (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim + return flops + + +class BasicLayer(nn.Module): + """A basic Swin Transformer layer for one stage. + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resulotion. + depth (int): Number of blocks. + num_heads (int): Number of attention heads. + window_size (int): Window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None + """ + + def __init__(self, dim, input_resolution, depth, num_heads, window_size, + mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., + drop_path=0., norm_layer=nn.LayerNorm, downsample=None): + + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.depth = depth + + self.blocks = nn.ModuleList([ + SwinTransformerBlock(dim=dim, input_resolution=input_resolution, + num_heads=num_heads, window_size=window_size, + shift_size=0 if (i % 2 == 0) else window_size // 2, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, qk_scale=qk_scale, + drop=drop, attn_drop=attn_drop, + drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, + norm_layer=norm_layer) + for i in range(depth)]) + if downsample is not None: + self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer) + else: + self.downsample = None + + def forward(self, x): + for blk in self.blocks: + x, _ = blk(x) + if self.downsample is not None: + x = self.downsample(x) + return x + + def forward_with_features(self, x): + fea = [] + for blk in self.blocks: + x, _ = blk(x) + fea.append(x) + if self.downsample is not None: + x = self.downsample(x) + return x, fea + + def forward_with_attention(self, x): + attns = [] + for blk in self.blocks: + x, attn = blk(x) + attns.append(attn) + if self.downsample is not None: + x = self.downsample(x) + return x, attns + + + def extra_repr(self) -> str: + return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}" + + def flops(self): + flops = 0 + for blk in self.blocks: + flops += blk.flops() + if self.downsample is not None: + flops += self.downsample.flops() + return flops + + +class PatchEmbed(nn.Module): + """ Image to Patch Embedding + """ + + def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, norm_layer=None): + super().__init__() + img_size = (img_size, img_size) + patch_size = (patch_size, patch_size) + patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]] + self.img_size = img_size + self.patch_size = patch_size + self.patches_resolution = patches_resolution + self.num_patches = patches_resolution[0] * patches_resolution[1] + + self.in_chans = in_chans + self.embed_dim = embed_dim + + self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) + if norm_layer is not None: + self.norm = norm_layer(embed_dim) + else: + self.norm = None + + def forward(self, x): + B, C, H, W = x.shape + + x = self.proj(x).flatten(2).transpose(1, 2) # B Ph*Pw C + if self.norm is not None: + x = self.norm(x) + return x + + + def flops(self): + Ho, Wo = self.patches_resolution + flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1]) + if self.norm is not None: + flops += Ho * Wo * self.embed_dim + return flops + +class SwinTransformer(nn.Module): + r""" Swin Transformer + A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` - + https://arxiv.org/pdf/2103.14030 + Args: + img_size (int | tuple(int)): Input image size. + patch_size (int | tuple(int)): Patch size. + in_chans (int): Number of input channels. + num_classes (int): Number of classes for classification head. + embed_dim (int): Embedding dimension. + depths (tuple(int)): Depth of Swin Transformer layers. + num_heads (tuple(int)): Number of attention heads in different layers. + window_size (int): Window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: Truee + qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. + drop_rate (float): Dropout rate. + attn_drop_rate (float): Attention dropout rate. + drop_path_rate (float): Stochastic depth rate. + norm_layer (nn.Module): normalization layer. + ape (bool): If True, add absolute position embedding to the patch embedding. + patch_norm (bool): If True, add normalization after patch embedding. + """ + + def __init__(self, img_size=224, patch_size=4, in_chans=3, num_classes=1000, + embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], + window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None, + drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1, + norm_layer=nn.LayerNorm, ape=False, patch_norm=True, **kwargs): + super().__init__() + + self.num_classes = num_classes + self.num_layers = len(depths) + self.embed_dim = embed_dim + self.ape = ape + self.patch_norm = patch_norm + self.num_features = int(embed_dim * 2 ** (self.num_layers - 1)) + self.mlp_ratio = mlp_ratio + + self.patch_embed = PatchEmbed( + img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim, + norm_layer=norm_layer if self.patch_norm else None) + num_patches = self.patch_embed.num_patches + patches_resolution = self.patch_embed.patches_resolution + self.patches_resolution = patches_resolution + + if self.ape: + self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim)) + trunc_normal_(self.absolute_pos_embed, std=.02) + + self.pos_drop = nn.Dropout(p=drop_rate) + + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule + self.layers = nn.ModuleList() + for i_layer in range(self.num_layers): + layer = BasicLayer(dim=int(embed_dim * 2 ** i_layer), + input_resolution=(patches_resolution[0] // (2 ** i_layer), + patches_resolution[1] // (2 ** i_layer)), + depth=depths[i_layer], + num_heads=num_heads[i_layer], + window_size=window_size, + mlp_ratio=self.mlp_ratio, + qkv_bias=qkv_bias, qk_scale=qk_scale, + drop=drop_rate, attn_drop=attn_drop_rate, + drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], + norm_layer=norm_layer, + downsample=PatchMerging if (i_layer < self.num_layers - 1) else None) + self.layers.append(layer) + + self.norm = norm_layer(self.num_features) + self.avgpool = nn.AdaptiveAvgPool1d(1) + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + @torch.jit.ignore + def no_weight_decay(self): + return {'absolute_pos_embed'} + + @torch.jit.ignore + def no_weight_decay_keywords(self): + # todo: to be implemented + return {'relative_position_bias_table'} + + def forward(self, x): + x = self.patch_embed(x) + if self.ape: + x = x + self.absolute_pos_embed + x = self.pos_drop(x) + + for layer in self.layers: + x = layer(x) + + x_region = self.norm(x) # B L C + x = self.avgpool(x_region.transpose(1, 2)) # B C 1 + x = torch.flatten(x, 1) + + return x + + + def forward_feature_maps(self, x): + x = self.patch_embed(x) + if self.ape: + x = x + self.absolute_pos_embed + x = self.pos_drop(x) + + for layer in self.layers: + x = layer(x) + + x_grid = self.norm(x) # B L C + x = self.avgpool(x_grid.transpose(1, 2)) # B C 1 + x = torch.flatten(x, 1) + + return x, x_grid + + + def forward_selfattention(self, x, n=1): + # n=1 return the last layer attn map; otherwise return attn maps in all layers + + + x = self.patch_embed(x) + if self.ape: + x = x + self.absolute_pos_embed + x = self.pos_drop(x) + + if n==1: + return self.forward_last_selfattention(x) + else: + return self.forward_all_selfattention(x) + + def forward_last_selfattention(self, x): + + for i, layer in enumerate(self.layers): + if i < len(self.layers) - 1: + x = layer(x) + else: + x, attns = layer.forward_with_attention(x) + return attns[-1] + + def forward_all_selfattention(self, x): + attn_out = [] + + for layer in self.layers: + x, attns = layer.forward_with_attention(x) + attn_out += attns + + return attn_out + + + def forward_return_n_last_blocks(self, x, n=1, return_patch_avgpool=False, depth=[]): + + num_blks = sum(depth) + start_idx = num_blks - n + + sum_cur = 0 + for i, d in enumerate(depth): + sum_cur_new = sum_cur + d + if start_idx >= sum_cur and start_idx < sum_cur_new: + start_stage = i + start_blk = start_idx - sum_cur + sum_cur = sum_cur_new + + + x = self.patch_embed(x) + if self.ape: + x = x + self.absolute_pos_embed + x = self.pos_drop(x) + + # we will return the averaged token features from the `n` last blocks + # note: there is no [CLS] token in Swin Transformer + output = [] + s = 0 + for i, layer in enumerate(self.layers): + x, fea = layer.forward_with_features(x) + + if i >= start_stage: + for x_ in fea[start_blk:]: + + if i == len(self.layers)-1: # use the norm in the last stage + x_ = self.norm(x_) + + x_avg = torch.flatten(self.avgpool(x_.transpose(1, 2)), 1) # B C + # print(f'Stage {i}, x_avg {x_avg.shape}') + output.append(x_avg) + + start_blk = 0 + + return torch.cat(output, dim=-1) + + + + def flops(self): + flops = 0 + flops += self.patch_embed.flops() + for i, layer in enumerate(self.layers): + flops += layer.flops() + if dist.get_rank() == 0: + print(f"GFLOPs layer_{i}: {layer.flops() / 1e9}") + flops += self.num_features * self.patches_resolution[0] * self.patches_resolution[1] // (2 ** self.num_layers) + flops += self.num_features * self.num_classes + return flops + + def init_weights(self, pretrained='', pretrained_layers=[], verbose=True): + if os.path.isfile(pretrained): + pretrained_dict = torch.load(pretrained, map_location='cpu') + logging.info(f'=> loading pretrained model {pretrained}') + model_dict = self.state_dict() + pretrained_dict = { + k: v for k, v in pretrained_dict.items() + if k in model_dict.keys() + } + need_init_state_dict = {} + for k, v in pretrained_dict.items(): + need_init = ( + k.split('.')[0] in pretrained_layers + or pretrained_layers[0] is '*' + or 'relative_position_index' not in k + or 'attn_mask' not in k + ) + + if need_init: + if verbose: + logging.info(f'=> init {k} from {pretrained}') + + if 'relative_position_bias_table' in k and v.size() != model_dict[k].size(): + relative_position_bias_table_pretrained = v + relative_position_bias_table_current = model_dict[k] + L1, nH1 = relative_position_bias_table_pretrained.size() + L2, nH2 = relative_position_bias_table_current.size() + if nH1 != nH2: + logging.info(f"Error in loading {k}, passing") + else: + if L1 != L2: + logging.info( + '=> load_pretrained: resized variant: {} to {}' + .format((L1, nH1), (L2, nH2)) + ) + S1 = int(L1 ** 0.5) + S2 = int(L2 ** 0.5) + relative_position_bias_table_pretrained_resized = torch.nn.functional.interpolate( + relative_position_bias_table_pretrained.permute(1, 0).view(1, nH1, S1, S1), + size=(S2, S2), + mode='bicubic') + v = relative_position_bias_table_pretrained_resized.view(nH2, L2).permute(1, 0) + + if 'absolute_pos_embed' in k and v.size() != model_dict[k].size(): + absolute_pos_embed_pretrained = v + absolute_pos_embed_current = model_dict[k] + _, L1, C1 = absolute_pos_embed_pretrained.size() + _, L2, C2 = absolute_pos_embed_current.size() + if C1 != C1: + logging.info(f"Error in loading {k}, passing") + else: + if L1 != L2: + logging.info( + '=> load_pretrained: resized variant: {} to {}' + .format((1, L1, C1), (1, L2, C2)) + ) + S1 = int(L1 ** 0.5) + S2 = int(L2 ** 0.5) + absolute_pos_embed_pretrained = absolute_pos_embed_pretrained.reshape(-1, S1, S1, C1) + absolute_pos_embed_pretrained = absolute_pos_embed_pretrained.permute(0, 3, 1, 2) + absolute_pos_embed_pretrained_resized = torch.nn.functional.interpolate( + absolute_pos_embed_pretrained, size=(S2, S2), mode='bicubic') + v = absolute_pos_embed_pretrained_resized.permute(0, 2, 3, 1).flatten(1, 2) + + need_init_state_dict[k] = v + self.load_state_dict(need_init_state_dict, strict=False) + + def freeze_pretrained_layers(self, frozen_layers=[]): + for name, module in self.named_modules(): + if ( + name.split('.')[0] in frozen_layers + or '.'.join(name.split('.')[0:2]) in frozen_layers + or (len(frozen_layers) > 0 and frozen_layers[0] is '*') + ): + for _name, param in module.named_parameters(): + param.requires_grad = False + logging.info( + '=> set param {} requires grad to False' + .format(name) + ) + for name, param in self.named_parameters(): + if ( + name.split('.')[0] in frozen_layers + or (len(frozen_layers) > 0 and frozen_layers[0] is '*') + and param.requires_grad is True + ): + param.requires_grad = False + logging.info( + '=> set param {} requires grad to False' + .format(name) + ) + return self + + +def get_swin(is_teacher=False): + args = get_args() + + if args.swin_backbone_type == "tiny": + embed_dim = 96 + depths = [2, 2, 6, 2] + num_heads = [3, 6, 12, 24] + drop_path_rate = 0.1 + elif args.swin_backbone_type == 'h3': + embed_dim = 384 + depths = [2, 2, 18, 2] + num_heads = [6, 12, 24, 48] + drop_path_rate = 0.2 + else: + embed_dim = 128 + depths = [2, 2, 18, 2] + num_heads = [4, 8, 16, 32] + drop_path_rate = 0.2 + + swin = SwinTransformer( + img_size=224, + in_chans=3, + num_classes=1000, + patch_size=4, + embed_dim=embed_dim, + depths=depths, + num_heads=num_heads, + window_size=7, + mlp_ratio=4, + qkv_bias=True, + drop_rate=0, + attn_drop_rate=0, + drop_path_rate=(0.0 if is_teacher else drop_path_rate), + norm_layer=partial(LayerNorm, eps=1e-6), + ape=False, + patch_norm=True, + ) + + return swin + diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/inpainting.py b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/inpainting.py new file mode 100644 index 0000000000000000000000000000000000000000..3d7a6da415e7ea5e4ac106a0ff7c31eae5f17682 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/inpainting.py @@ -0,0 +1,152 @@ +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. +i +import math +import apex +import einops +import torch +import torch.nn.functional as F +from megatron import get_args, print_rank_0 +from megatron.model.utils import get_linear_layer +from megatron.model.vision.vit_backbone import VitBackbone +from megatron.model.module import MegatronModule +from megatron.model.vision.mit_backbone import mit_b3 +from megatron.model.vision.utils import resize_ + + +class VitInpaintingModel(MegatronModule): + + def __init__(self, config, pre_process=True, post_process=True): + super(VitInpaintingModel, self).__init__() + args = get_args() + + self.pre_process = pre_process + self.post_process = post_process + self.hidden_size = config.hidden_size + self.backbone = VitBackbone( + config=config, + pre_process=self.pre_process, + post_process=self.post_process, + class_token=False, + ) + self.patch_dim = args.patch_dim + self.img_h = args.img_h + self.img_w = args.img_w + self.seq_length = args.seq_length + # full mask + + if self.post_process: + self.linear_decoder = get_linear_layer( + self.hidden_size, + self.backbone.flatten_dim, + torch.nn.init.zeros_, + gather_params_on_init=args.zero_stage == 3 + ) + + def set_input_tensor(self, input_tensor): + self.backbone.set_input_tensor(input_tensor) + + def forward(self, input): + + hidden_states = self.backbone(input) + + if not self.post_process: + return hidden_states + decoded_output = self.linear_decoder(hidden_states) + output = einops.rearrange( + decoded_output, + "b (h w) (p1 p2 c) -> b c (h p1) (w p2)", + p1=self.patch_dim, + p2=self.patch_dim, + h=self.img_h//self.patch_dim, + w=self.img_w//self.patch_dim, + ) + + return output + + +class MLP(torch.nn.Module): + """ + Linear Embedding + """ + def __init__(self, input_dim=2048, embed_dim=768): + super().__init__() + self.proj = torch.nn.Linear(input_dim, embed_dim) + + def forward(self, x): + x = x.flatten(2).transpose(1, 2) + x = self.proj(x) + return x + + +class MitInpaintingModel(MegatronModule): + """Mix vision Transformer Model.""" + + def __init__(self, pre_process=True, post_process=True): + super(MitInpaintingModel, self).__init__() + self.pre_process = pre_process + self.post_process = post_process + + args = get_args() + self.patch_dim = args.patch_dim + self.img_h = args.img_h + self.img_w = args.img_w + self.flatten_dim = self.patch_dim * self.patch_dim * 3 + self.backbone = mit_b3() + + self.in_channels = [64, 128, 320, 512] + self.embedding_dim = 768 + + c1_in_channels, c2_in_channels, c3_in_channels, c4_in_channels = self.in_channels + + self.linear_c4 = MLP(input_dim=c4_in_channels, embed_dim=self.embedding_dim) + self.linear_c3 = MLP(input_dim=c3_in_channels, embed_dim=self.embedding_dim) + self.linear_c2 = MLP(input_dim=c2_in_channels, embed_dim=self.embedding_dim) + self.linear_c1 = MLP(input_dim=c1_in_channels, embed_dim=self.embedding_dim) + + self.conv_fuse = torch.nn.Conv2d(self.embedding_dim*4, self.embedding_dim, 1, 1, bias=False) + self.norm = apex.parallel.SyncBatchNorm(self.embedding_dim) + self.dropout = torch.nn.Dropout2d(0.1) + + self.linear_pred = torch.nn.Conv2d(self.embedding_dim, self.flatten_dim, kernel_size=1) + + def set_input_tensor(self, input_tensor): + """See megatron.model.transformer.set_input_tensor()""" + pass + + def forward(self, input): + c1, c2, c3, c4 = self.backbone(input) + + n, _, h, w = c4.shape + _c4 = self.linear_c4(c4).permute(0, 2, 1).reshape(n, -1, c4.shape[2], c4.shape[3]) + _c4 = resize(_c4, size=c1.size()[2:], mode='bilinear', align_corners=False) + + _c3 = self.linear_c3(c3).permute(0, 2, 1).reshape(n, -1, c3.shape[2], c3.shape[3]) + _c3 = resize(_c3, size=c1.size()[2:], mode='bilinear', align_corners=False) + + _c2 = self.linear_c2(c2).permute(0, 2, 1).reshape(n, -1, c2.shape[2], c2.shape[3]) + _c2 = resize(_c2, size=c1.size()[2:], mode='bilinear', align_corners=False) + + _c1 = self.linear_c1(c1).permute(0, 2, 1).reshape(n, -1, c1.shape[2], c1.shape[3]) + + _c = torch.cat([_c4, _c3, _c2, _c1], dim=1) + _c = self.conv_fuse(_c) + + x = self.norm(_c) + x = F.relu(x, inplace=True) + x = self.dropout(x) + + x = self.linear_pred(x) + + output = einops.rearrange( + x, + "b (c p1 p2) h w -> b c (h p1) (w p2)", + p1=self.patch_dim, + p2=self.patch_dim, + h=self.img_h//self.patch_dim, + w=self.img_w//self.patch_dim, + ) + + return output diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/knn_monitor.py b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/knn_monitor.py new file mode 100644 index 0000000000000000000000000000000000000000..a7d79854eb51f24443fcdce9e029df5512503bf9 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/knn_monitor.py @@ -0,0 +1,129 @@ +import torch.nn.functional as F +import torch +from megatron import print_rank_0, get_args +from megatron.core import mpu +from megatron.data.vit_dataset import ClassificationTransform +from megatron.data.image_folder import ImageFolder + +_FEATURE_BANK = None + + +def build_data_loader(dataset, drop_last=True, shuffle=False): + """Data loader. Note that batch-size is the local (per GPU) batch-size.""" + # Sampler. + args = get_args() + micro_batch_size = 16 + num_workers = args.num_workers + 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, + drop_last=drop_last, shuffle=shuffle + ) + + # 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=not drop_last, + pin_memory=True, + ) + return data_loader + + +def compute_feature_bank(model): + args = get_args() + global _FEATURE_BANK + feature_bank = [] + feature_label = [] + + train_ds = ImageFolder( + root=args.data_path[0], + transform=ClassificationTransform((args.img_h, args.img_w), train=False), + data_per_class_fraction=1.0 + ) + classes = len(train_ds.classes) + dataloader = build_data_loader(train_ds) + + for m in model: + m.eval() + + with torch.no_grad(): + for i, batch in enumerate(dataloader): + images = batch[0].cuda().contiguous() + labels = batch[1].cuda().contiguous() + student_feature, teacher_feature = model[0](images) + feature = F.normalize(teacher_feature.float(), dim=1) + feature_bank.append(feature) + feature_label.append(labels) + + for m in model: + m.train() + + # [N', D] + feature_bank = torch.cat(feature_bank, dim=0).contiguous() + feature_label = torch.cat(feature_label, dim=0).contiguous() + + feature_banks = [torch.zeros_like(feature_bank) + for i in range(mpu.get_data_parallel_world_size())] + torch.distributed.all_gather(feature_banks, + feature_bank, + group=mpu.get_data_parallel_group()) + + assert torch.all(torch.eq(feature_banks[mpu.get_data_parallel_rank()], + feature_bank)) + + feature_labels = [torch.zeros_like(feature_label) + for i in range(mpu.get_data_parallel_world_size())] + torch.distributed.all_gather(feature_labels, + feature_label, + group=mpu.get_data_parallel_group()) + + # [D, N] + feature_banks = torch.cat(feature_banks, dim=0).t().contiguous() + # [N] + feature_labels = torch.cat(feature_labels, dim=0).contiguous() + print_rank_0("feature_banks size is {}".format(feature_banks.size())) + print_rank_0("feature labels size is {}".format(feature_labels.size())) + + _FEATURE_BANK = (feature_banks, feature_labels, classes) + + +def get_feature_bank(): + global _FEATURE_BANK + assert _FEATURE_BANK is not None + return _FEATURE_BANK + + +# knn monitor as in InstDisc https://arxiv.org/abs/1805.01978 +# implementation follows http://github.com/zhirongw/lemniscate.pytorch and +# https://github.com/leftthomas/SimCLR +def knn_predict(feature, feature_bank, feature_labels, classes, knn_k, knn_t): + # compute cos similarity between each feature vector and feature bank ---> [B, N] + sim_matrix = torch.mm(feature, feature_bank) + # [B, K] + sim_weight, sim_indices = sim_matrix.topk(k=knn_k, dim=-1) + # [B, K] + sim_labels = torch.gather(feature_labels.expand(feature.size(0), -1), + dim=-1, + index=sim_indices) + sim_weight = (sim_weight / knn_t).exp() + + # counts for each class + one_hot_label = torch.zeros(feature.size(0) * knn_k, + classes, + device=sim_labels.device) + # [B*K, C] + one_hot_label = one_hot_label.scatter(dim=-1, + index=sim_labels.view(-1, 1), + value=1.0) + # weighted score ---> [B, C] + pred_scores = torch.sum( + one_hot_label.view(feature.size(0), -1, classes) * sim_weight.unsqueeze(dim=-1), + dim=1) + + pred_labels = pred_scores.argsort(dim=-1, descending=True) + return pred_labels diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/mit_backbone.py b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/mit_backbone.py new file mode 100644 index 0000000000000000000000000000000000000000..c67ca2c62bbd380751998954be16fdb93fef38f4 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/mit_backbone.py @@ -0,0 +1,420 @@ +# --------------------------------------------------------------- +# Copyright (c) 2021, NVIDIA Corporation. All rights reserved. +# +# This work is licensed under the NVIDIA Source Code License +# found in the LICENSE file in the root directory of this +# source tree. +# --------------------------------------------------------------- +import math +import torch +import torch.nn as nn +import torch.nn.functional as F +from functools import partial +from torch.nn.init import trunc_normal_ +from megatron.model.transformer import DropPath +from megatron.model import LayerNorm + + +class Mlp(nn.Module): + def __init__(self, + in_features, + hidden_features=None, + out_features=None, + act_layer=nn.GELU, + drop=0.): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + self.dwconv = DWConv(hidden_features) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + elif isinstance(m, nn.Conv2d): + fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + fan_out //= m.groups + m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) + if m.bias is not None: + m.bias.data.zero_() + + def forward(self, x, H, W): + x = self.fc1(x) + x = self.dwconv(x, H, W) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +class Attention(nn.Module): + def __init__(self, + dim, + num_heads=8, + qkv_bias=False, + qk_scale=None, + attn_drop=0., + proj_drop=0., + sr_ratio=1): + super().__init__() + assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}." + + self.dim = dim + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = qk_scale or head_dim ** -0.5 + + self.q = nn.Linear(dim, dim, bias=qkv_bias) + self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + + self.sr_ratio = sr_ratio + if sr_ratio > 1: + self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio) + self.norm = LayerNorm(dim) + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + elif isinstance(m, nn.Conv2d): + fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + fan_out //= m.groups + m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) + if m.bias is not None: + m.bias.data.zero_() + + def forward(self, x, H, W): + B, N, C = x.shape + q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) + + if self.sr_ratio > 1: + x_ = x.permute(0, 2, 1).reshape(B, C, H, W) + x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1) + x_ = self.norm(x_) + kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) + else: + kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) + k, v = kv[0], kv[1] + + attn = (q @ k.transpose(-2, -1)) * self.scale + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + + x = (attn @ v).transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + + return x + + +class Block(nn.Module): + + def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., + drop_path=0., act_layer=nn.GELU, norm_layer=LayerNorm, sr_ratio=1): + super().__init__() + self.norm1 = norm_layer(dim) + self.attn = Attention( + dim, + num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, + attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio) + # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here + self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + elif isinstance(m, nn.Conv2d): + fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + fan_out //= m.groups + m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) + if m.bias is not None: + m.bias.data.zero_() + + def forward(self, x, H, W): + x = x + self.drop_path(self.attn(self.norm1(x), H, W)) + x = x + self.drop_path(self.mlp(self.norm2(x), H, W)) + + return x + + +class OverlapPatchEmbed(nn.Module): + """ Image to Patch Embedding + """ + + def __init__(self, img_size=224, patch_size=7, stride=4, in_chans=3, embed_dim=768): + super().__init__() + img_size = (img_size, img_size) + patch_size = (patch_size, patch_size) + + self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride, + padding=(patch_size[0] // 2, patch_size[1] // 2)) + self.norm = LayerNorm(embed_dim) + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + elif isinstance(m, nn.Conv2d): + fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + fan_out //= m.groups + m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) + if m.bias is not None: + m.bias.data.zero_() + + def forward(self, x): + x = self.proj(x) + _, _, H, W = x.shape + x = x.flatten(2).transpose(1, 2) + x = self.norm(x) + + return x, H, W + + +class MixVisionTransformer(nn.Module): + def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dims=[64, 128, 256, 512], + num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0., + attn_drop_rate=0., drop_path_rate=0., norm_layer=LayerNorm, + depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1], output_avg=False): + super().__init__() + self.num_classes = num_classes + self.depths = depths + self.output_avg = output_avg + + # patch_embed + self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_chans=in_chans, + embed_dim=embed_dims[0]) + self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_chans=embed_dims[0], + embed_dim=embed_dims[1]) + self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_chans=embed_dims[1], + embed_dim=embed_dims[2]) + self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_chans=embed_dims[2], + embed_dim=embed_dims[3]) + + # transformer encoder + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule + cur = 0 + self.block1 = nn.ModuleList([Block( + dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale, + drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, + sr_ratio=sr_ratios[0]) + for i in range(depths[0])]) + self.norm1 = norm_layer(embed_dims[0]) + + cur += depths[0] + self.block2 = nn.ModuleList([Block( + dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale, + drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, + sr_ratio=sr_ratios[1]) + for i in range(depths[1])]) + self.norm2 = norm_layer(embed_dims[1]) + + cur += depths[1] + self.block3 = nn.ModuleList([Block( + dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale, + drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, + sr_ratio=sr_ratios[2]) + for i in range(depths[2])]) + self.norm3 = norm_layer(embed_dims[2]) + + cur += depths[2] + self.block4 = nn.ModuleList([Block( + dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale, + drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, + sr_ratio=sr_ratios[3]) + for i in range(depths[3])]) + self.norm4 = norm_layer(embed_dims[3]) + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + elif isinstance(m, nn.Conv2d): + fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + fan_out //= m.groups + m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) + if m.bias is not None: + m.bias.data.zero_() + + def reset_drop_path(self, drop_path_rate): + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))] + cur = 0 + for i in range(self.depths[0]): + self.block1[i].drop_path.drop_prob = dpr[cur + i] + + cur += self.depths[0] + for i in range(self.depths[1]): + self.block2[i].drop_path.drop_prob = dpr[cur + i] + + cur += self.depths[1] + for i in range(self.depths[2]): + self.block3[i].drop_path.drop_prob = dpr[cur + i] + + cur += self.depths[2] + for i in range(self.depths[3]): + self.block4[i].drop_path.drop_prob = dpr[cur + i] + + def freeze_patch_emb(self): + self.patch_embed1.requires_grad = False + + def forward_features(self, x): + B = x.shape[0] + outs = [] + + # stage 1 + x, H, W = self.patch_embed1(x) + for i, blk in enumerate(self.block1): + x = blk(x, H, W) + x = self.norm1(x) + x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() + outs.append(x) + + # stage 2 + x, H, W = self.patch_embed2(x) + for i, blk in enumerate(self.block2): + x = blk(x, H, W) + x = self.norm2(x) + x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() + outs.append(x) + + # stage 3 + x, H, W = self.patch_embed3(x) + for i, blk in enumerate(self.block3): + x = blk(x, H, W) + x = self.norm3(x) + x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() + outs.append(x) + + # stage 4 + x, H, W = self.patch_embed4(x) + for i, blk in enumerate(self.block4): + x = blk(x, H, W) + x = self.norm4(x) + if not self.output_avg: + x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() + outs.append(x) + + return outs + + def forward(self, x): + x = self.forward_features(x) + + if self.output_avg: + x = x[3].mean(dim=1) + + return x + + +class DWConv(nn.Module): + def __init__(self, dim=768): + super(DWConv, self).__init__() + self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim) + + def forward(self, x, H, W): + B, N, C = x.shape + x = x.transpose(1, 2).view(B, C, H, W) + x = self.dwconv(x) + x = x.flatten(2).transpose(1, 2) + + return x + +class mit_b0(MixVisionTransformer): + def __init__(self, **kwargs): + super(mit_b0, self).__init__( + patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], + qkv_bias=True, norm_layer=partial(LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1], + drop_rate=0.0, drop_path_rate=0.1) + + +class mit_b1(MixVisionTransformer): + def __init__(self, **kwargs): + super(mit_b1, self).__init__( + patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], + qkv_bias=True, norm_layer=partial(LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1], + drop_rate=0.0, drop_path_rate=0.1) + + +class mit_b2(MixVisionTransformer): + def __init__(self, **kwargs): + super(mit_b2, self).__init__( + patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], + qkv_bias=True, norm_layer=partial(LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1], + drop_rate=0.0, drop_path_rate=0.1) + + +class mit_b3(MixVisionTransformer): + def __init__(self, **kwargs): + super(mit_b3, self).__init__( + patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], + qkv_bias=True, norm_layer=partial(LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1], + drop_rate=0.0, drop_path_rate=0.1) + +class mit_b3_avg(MixVisionTransformer): + def __init__(self, drop_path_rate=0.1, **kwargs): + super(mit_b3_avg, self).__init__( + patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], + qkv_bias=True, norm_layer=partial(LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1], + drop_rate=0.0, drop_path_rate=drop_path_rate, output_avg=True) + +class mit_b4(MixVisionTransformer): + def __init__(self, **kwargs): + super(mit_b4, self).__init__( + patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], + qkv_bias=True, norm_layer=partial(LayerNorm, eps=1e-6), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1], + drop_rate=0.0, drop_path_rate=0.1) + +class mit_b5(MixVisionTransformer): + def __init__(self, **kwargs): + super(mit_b5, self).__init__( + patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], + qkv_bias=True, norm_layer=partial(LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1], + drop_rate=0.0, drop_path_rate=0.1) + +class mit_b5_avg(MixVisionTransformer): + def __init__(self, drop_path_rate=0.1, **kwargs): + super(mit_b5_avg, self).__init__( + patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], + qkv_bias=True, norm_layer=partial(LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1], + drop_rate=0.0, drop_path_rate=drop_path_rate, output_avg=True) + diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/swin_backbone.py b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/swin_backbone.py new file mode 100644 index 0000000000000000000000000000000000000000..9a622c7070f5a8335b56ce01398e3e464e3fef6a --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/swin_backbone.py @@ -0,0 +1,625 @@ +# Copyright (c) 2021 Microsoft +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. +# -------------------------------------------------------- +# Swin Transformer +# -------------------------------------------------------- + +import torch +import torch.nn as nn +import torch.utils.checkpoint as checkpoint +from timm.models.layers import DropPath, to_2tuple, trunc_normal_ +from math import sqrt + +from megatron import get_args +from functools import partial + + +class Mlp(nn.Module): + def __init__(self, in_features, hidden_features=None, + out_features=None, act_layer=nn.GELU, drop=0.): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +def window_partition(x, window_size): + """ + Args: + x: (B, H, W, C) + window_size (int): window size + + Returns: + windows: (num_windows*B, window_size, window_size, C) + """ + B, H, W, C = x.shape + x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) + windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + return windows + + +def window_reverse(windows, window_size, H, W): + """ + Args: + windows: (num_windows*B, window_size, window_size, C) + window_size (int): Window size + H (int): Height of image + W (int): Width of image + + Returns: + x: (B, H, W, C) + """ + B = int(windows.shape[0] / (H * W / window_size / window_size)) + x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) + return x + + +class WindowAttention(nn.Module): + r""" Window based multi-head self attention (W-MSA) module with relative position bias. + It supports both of shifted and non-shifted window. + + Args: + dim (int): Number of input channels. + window_size (tuple[int]): The height and width of the window. + num_heads (int): Number of attention heads. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set + attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 + proj_drop (float, optional): Dropout ratio of output. Default: 0.0 + """ + + def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.): + + super().__init__() + self.dim = dim + self.window_size = window_size # Wh, Ww + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = qk_scale or head_dim ** -0.5 + + # define a parameter table of relative position bias + self.relative_position_bias_table = nn.Parameter( + torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH + + # get pair-wise relative position index for each token inside the window + coords_h = torch.arange(self.window_size[0]) + coords_w = torch.arange(self.window_size[1]) + coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww + coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww + relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww + relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 + relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 + relative_coords[:, :, 1] += self.window_size[1] - 1 + relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 + relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww + self.register_buffer("relative_position_index", relative_position_index) + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + + trunc_normal_(self.relative_position_bias_table, std=.02) + self.softmax = nn.Softmax(dim=-1) + + def forward(self, x, mask=None): + """ + Args: + x: input features with shape of (num_windows*B, N, C) + mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None + """ + B_, N, C = x.shape + qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) + q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) + + q = q * self.scale + attn = (q @ k.transpose(-2, -1)) + + relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view( + self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH + relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww + attn = attn + relative_position_bias.unsqueeze(0) + + if mask is not None: + nW = mask.shape[0] + attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0) + attn = attn.view(-1, self.num_heads, N, N) + attn = self.softmax(attn) + else: + attn = self.softmax(attn) + + attn = self.attn_drop(attn) + + x = (attn @ v).transpose(1, 2).reshape(B_, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + def extra_repr(self) -> str: + return f'dim={self.dim}, window_size={self.window_size}, num_heads={self.num_heads}' + + def flops(self, N): + # calculate flops for 1 window with token length of N + flops = 0 + # qkv = self.qkv(x) + flops += N * self.dim * 3 * self.dim + # attn = (q @ k.transpose(-2, -1)) + flops += self.num_heads * N * (self.dim // self.num_heads) * N + # x = (attn @ v) + flops += self.num_heads * N * N * (self.dim // self.num_heads) + # x = self.proj(x) + flops += N * self.dim * self.dim + return flops + + +class SwinTransformerBlock(nn.Module): + r""" Swin Transformer Block. + + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resulotion. + num_heads (int): Number of attention heads. + window_size (int): Window size. + shift_size (int): Shift size for SW-MSA. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float, optional): Stochastic depth rate. Default: 0.0 + act_layer (nn.Module, optional): Activation layer. Default: nn.GELU + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + """ + + def __init__(self, dim, input_resolution, num_heads, window_size=7, shift_size=0, + mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0., + act_layer=nn.GELU, norm_layer=nn.LayerNorm): + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.num_heads = num_heads + self.window_size = window_size + self.shift_size = shift_size + self.mlp_ratio = mlp_ratio + if min(self.input_resolution) <= self.window_size: + # if window size is larger than input resolution, we don't partition windows + self.shift_size = 0 + self.window_size = min(self.input_resolution) + assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size" + + self.norm1 = norm_layer(dim) + self.attn = WindowAttention( + dim, window_size=to_2tuple(self.window_size), num_heads=num_heads, + qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) + + self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) + + self.H = input_resolution[0] + self.W = input_resolution[1] + + self.attn_mask_dict = {} + + def create_attn_mask(self, H, W): + # calculate attention mask for SW-MSA + + Hp = int(np.ceil(H / self.window_size)) * self.window_size + Wp = int(np.ceil(W / self.window_size)) * self.window_size + img_mask = torch.zeros((1, Hp, Wp, 1)) # 1 Hp Wp 1 + h_slices = (slice(0, -self.window_size), + slice(-self.window_size, -self.shift_size), + slice(-self.shift_size, None)) + w_slices = (slice(0, -self.window_size), + slice(-self.window_size, -self.shift_size), + slice(-self.shift_size, None)) + cnt = 0 + for h in h_slices: + for w in w_slices: + img_mask[:, h, w, :] = cnt + cnt += 1 + + mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1 + mask_windows = mask_windows.view(-1, self.window_size * self.window_size) + attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) + attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) + + return attn_mask + + + def forward(self, x): + B, L, C = x.shape + H = int(sqrt(L)) + W = H + + shortcut = x + x = self.norm1(x) + x = x.view(B, H, W, C) + + # cyclic shift + if self.shift_size > 0: + shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) + else: + shifted_x = x + + # partition windows + x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C + x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C + + # W-MSA/SW-MSA + attn_windows = self.attn(x_windows, mask=self.attn_mask) # nW*B, window_size*window_size, C + + # merge windows + attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) + shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C + + # reverse cyclic shift + if self.shift_size > 0: + x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) + else: + x = shifted_x + x = x.view(B, H * W, C) + + # FFN + x = shortcut + self.drop_path(x) + x = x + self.drop_path(self.mlp(self.norm2(x))) + + return x + + def extra_repr(self) -> str: + return f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " \ + f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}" + + def flops(self): + flops = 0 + H, W = self.input_resolution + # norm1 + flops += self.dim * H * W + # W-MSA/SW-MSA + nW = H * W / self.window_size / self.window_size + flops += nW * self.attn.flops(self.window_size * self.window_size) + # mlp + flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio + # norm2 + flops += self.dim * H * W + return flops + + +class PatchMerging(nn.Module): + r""" Patch Merging Layer. + + Args: + input_resolution (tuple[int]): Resolution of input feature. + dim (int): Number of input channels. + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + """ + + def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm): + super().__init__() + self.input_resolution = input_resolution + self.dim = dim + self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) + self.norm = norm_layer(4 * dim) + + def forward(self, x): + """ + x: B, H*W, C + """ + H, W = self.input_resolution + B, L, C = x.shape + assert L == H * W, "input feature has wrong size" + assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even." + + x = x.view(B, H, W, C) + + x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C + x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C + x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C + x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C + x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C + x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C + + x = self.norm(x) + x = self.reduction(x) + + return x + + def extra_repr(self) -> str: + return f"input_resolution={self.input_resolution}, dim={self.dim}" + + def flops(self): + H, W = self.input_resolution + flops = H * W * self.dim + flops += (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim + return flops + + +class BasicLayer(nn.Module): + """ A basic Swin Transformer layer for one stage. + + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resolution. + depth (int): Number of blocks. + num_heads (int): Number of attention heads. + window_size (int): Local window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. + """ + + def __init__(self, dim, input_resolution, depth, num_heads, window_size, + mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., + drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False): + + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.depth = depth + self.use_checkpoint = use_checkpoint + + # build blocks + self.blocks = nn.ModuleList([ + SwinTransformerBlock(dim=dim, input_resolution=input_resolution, + num_heads=num_heads, window_size=window_size, + shift_size=0 if (i % 2 == 0) else window_size // 2, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, qk_scale=qk_scale, + drop=drop, attn_drop=attn_drop, + drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, + norm_layer=norm_layer) + for i in range(depth)]) + + # patch merging layer + if downsample is not None: + self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer) + else: + self.downsample = None + + def forward(self, x): + for blk in self.blocks: + if self.use_checkpoint: + x = checkpoint.checkpoint(blk, x) + else: + x = blk(x) + x_b4_ds = x + if self.downsample is not None: + x = self.downsample(x) + return x_b4_ds, x + + def extra_repr(self) -> str: + return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}" + + def flops(self): + flops = 0 + for blk in self.blocks: + flops += blk.flops() + if self.downsample is not None: + flops += self.downsample.flops() + return flops + + +class PatchEmbed(nn.Module): + r""" Image to Patch Embedding + + Args: + img_size (int): Image size. Default: 224. + patch_size (int): Patch token size. Default: 4. + in_chans (int): Number of input image channels. Default: 3. + embed_dim (int): Number of linear projection output channels. Default: 96. + norm_layer (nn.Module, optional): Normalization layer. Default: None + """ + + def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None): + super().__init__() + img_size = to_2tuple(img_size) + patch_size = to_2tuple(patch_size) + patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]] + self.img_size = img_size + self.patch_size = patch_size + self.patches_resolution = patches_resolution + self.num_patches = patches_resolution[0] * patches_resolution[1] + + self.in_chans = in_chans + self.embed_dim = embed_dim + + self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) + if norm_layer is not None: + self.norm = norm_layer(embed_dim) + else: + self.norm = None + + def forward(self, x): + B, C, H, W = x.shape + # FIXME look at relaxing size constraints + assert H == self.img_size[0] and W == self.img_size[1], \ + f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." + x = self.proj(x).flatten(2).transpose(1, 2) # B Ph*Pw C + if self.norm is not None: + x = self.norm(x) + return x + + def flops(self): + Ho, Wo = self.patches_resolution + flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1]) + if self.norm is not None: + flops += Ho * Wo * self.embed_dim + return flops + + +class SwinTransformer(nn.Module): + r""" Swin Transformer + A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` - + https://arxiv.org/pdf/2103.14030 + + Args: + img_size (int | tuple(int)): Input image size. Default 224 + patch_size (int | tuple(int)): Patch size. Default: 4 + in_chans (int): Number of input image channels. Default: 3 + embed_dim (int): Patch embedding dimension. Default: 96 + depths (tuple(int)): Depth of each Swin Transformer layer. + num_heads (tuple(int)): Number of attention heads in different layers. + window_size (int): Window size. Default: 7 + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4 + qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. Default: None + drop_rate (float): Dropout rate. Default: 0 + attn_drop_rate (float): Attention dropout rate. Default: 0 + drop_path_rate (float): Stochastic depth rate. Default: 0.1 + norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. + ape (bool): If True, add absolute position embedding to the patch embedding. Default: False + patch_norm (bool): If True, add normalization after patch embedding. Default: True + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False + """ + + def __init__(self, img_size=224, patch_size=4, in_chans=3, + embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], + window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None, + drop_rate=0., attn_drop_rate=0., drop_path_rate=0.3, + norm_layer=partial(nn.LayerNorm, eps=1e-6), ape=False, patch_norm=True, + use_checkpoint=False, output_avg=False, **kwargs): + super().__init__() + + self.num_layers = len(depths) + self.embed_dim = embed_dim + self.ape = ape + self.patch_norm = patch_norm + self.num_features = int(embed_dim * 2 ** (self.num_layers - 1)) + self.mlp_ratio = mlp_ratio + self.img_size = to_2tuple(img_size) + self.patch_size = to_2tuple(patch_size) + self.output_avg = output_avg + + # split image into non-overlapping patches + self.patch_embed = PatchEmbed( + img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim, + norm_layer=norm_layer if self.patch_norm else None) + num_patches = self.patch_embed.num_patches + patches_resolution = self.patch_embed.patches_resolution + self.patches_resolution = patches_resolution + + # absolute position embedding + if self.ape: + self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim)) + trunc_normal_(self.absolute_pos_embed, std=.02) + + self.pos_drop = nn.Dropout(p=drop_rate) + + # stochastic depth + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule + + # build layers + self.layers = nn.ModuleList() + for i_layer in range(self.num_layers): + layer = BasicLayer(dim=int(embed_dim * 2 ** i_layer), + input_resolution=(patches_resolution[0] // (2 ** i_layer), + patches_resolution[1] // (2 ** i_layer)), + depth=depths[i_layer], + num_heads=num_heads[i_layer], + window_size=window_size, + mlp_ratio=self.mlp_ratio, + qkv_bias=qkv_bias, qk_scale=qk_scale, + drop=drop_rate, attn_drop=attn_drop_rate, + drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], + norm_layer=norm_layer, + downsample=PatchMerging if (i_layer < self.num_layers - 1) else None, + use_checkpoint=use_checkpoint) + self.layers.append(layer) + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + @torch.jit.ignore + def no_weight_decay(self): + return {'absolute_pos_embed'} + + @torch.jit.ignore + def no_weight_decay_keywords(self): + return {'relative_position_bias_table'} + + def forward(self, x): + x = self.patch_embed(x) + if self.ape: + x = x + self.absolute_pos_embed + x = self.pos_drop(x) + + h = self.img_size[0] // self.patch_size[0] + w = self.img_size[1] // self.patch_size[1] + outs = [] + + for i, layer in enumerate(self.layers): + px, x = layer(x) + b, n, c = px.shape + + if i != len(self.layers) - 1 or not self.output_avg: + px = px.permute(0, 2, 1).contiguous() + px = px.reshape(b, c, h, w) + # is this a fair assumption ?? i think it's baked into the architecture + h, w = h//2, w//2 + outs.append(px) + + if self.output_avg: + return outs[-1].mean(dim=1) + + return outs + + def flops(self): + flops = 0 + flops += self.patch_embed.flops() + for i, layer in enumerate(self.layers): + flops += layer.flops() + flops += self.num_features * self.patches_resolution[0] * self.patches_resolution[1] // (2 ** self.num_layers) + flops += self.num_features * self.num_classes + return flops + + +def get_swin(drop_path_rate=0.3, output_avg=False): + args = get_args() + + window_size = 7 + embed_dim = 128 + depths = [2, 2, 18, 2] + num_heads = [4, 8, 16, 32] + swin = SwinTransformer( + img_size=(args.img_h, args.img_w,), + in_chans=3, + patch_size=args.patch_dim, + embed_dim=embed_dim, + depths=depths, + num_heads=num_heads, + window_size=window_size, + drop_path_rate=drop_path_rate, + output_avg=output_avg, + ) + + return swin + diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/utils.py b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b4068912c8bb234eff54d6b4feae499f7e8ab30c --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/utils.py @@ -0,0 +1,27 @@ +import warnings +import torch +import torch.nn.functional as F + + +def resize(input, + size=None, + scale_factor=None, + mode='nearest', + align_corners=None, + warning=True): + if warning: + if size is not None and align_corners: + input_h, input_w = tuple(int(x) for x in input.shape[2:]) + output_h, output_w = tuple(int(x) for x in size) + if output_h > input_h or output_w > output_h: + if ((output_h > 1 and output_w > 1 and input_h > 1 + and input_w > 1) and (output_h - 1) % (input_h - 1) + and (output_w - 1) % (input_w - 1)): + warnings.warn( + f'When align_corners={align_corners}, ' + 'the output would more aligned if ' + f'input size {(input_h, input_w)} is `x+1` and ' + f'out size {(output_h, output_w)} is `nx+1`') + if isinstance(size, torch.Size): + size = tuple(int(x) for x in size) + return F.interpolate(input, size, scale_factor, mode, align_corners) diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/vit_backbone.py b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/vit_backbone.py new file mode 100644 index 0000000000000000000000000000000000000000..1efef9c17a8003611a75029d957657237c2436c7 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/model/vision/vit_backbone.py @@ -0,0 +1,245 @@ +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. + +"""Vision Transformer(VIT) model.""" + +import math +import einops +import torch +import apex +import torch.nn.functional as F +from megatron import get_args +from megatron.model.transformer import ParallelTransformer +from megatron.model.utils import ( + get_linear_layer, + init_method_normal, + scaled_init_method_normal, +) +from megatron.model.module import MegatronModule + +CLASS_TOKEN_LENGTH = 8 + +class VitMlpHead(MegatronModule): + """Pooler layer. + + Pool hidden states of a specific token (for example start of the + sequence) and add a linear transformation followed by a tanh. + + Arguments: + hidden_size: hidden size + init_method: weight initialization method for the linear layer. + bias is set to zero. + """ + + def __init__(self, hidden_size, num_classes): + super(VitMlpHead, self).__init__() + self.dense_in = torch.nn.Linear(hidden_size, hidden_size) + self.relu = torch.nn.ReLU() + self.dense_out = torch.nn.Linear(hidden_size, num_classes) + torch.nn.init.constant_(self.dense_out.bias, -10) + + def forward(self, hidden_states): + # hidden_states: [b, 1, h] + # sequence_index: index of the token to pool. + dense_in_result = self.dense_in(hidden_states) + tanh_result = torch.tanh(dense_in_result) + dense_out_result = self.dense_out(tanh_result) + return dense_out_result + + +def isPerfectSquare(x): + if(x >= 0): + sr = math.sqrt(x) + return (int(sr) * int(sr) == x) + return False + + +def twod_interpolate_position_embeddings_hook( + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, +): + + args = get_args() + num_patches_per_dim_h = args.img_h // args.patch_dim + num_patches_per_dim_w = args.img_w // args.patch_dim + num_patches = num_patches_per_dim_h * num_patches_per_dim_w + hidden_size = args.hidden_size + + key = prefix + "weight" + + assert key in state_dict + if key in state_dict: + input_param = state_dict[key] + + input_seq_len = input_param.shape[0] + assert(isPerfectSquare(input_seq_len) or isPerfectSquare(input_seq_len - CLASS_TOKEN_LENGTH)) + input_has_class_token = not isPerfectSquare(input_seq_len) + num_tok_input = input_seq_len - CLASS_TOKEN_LENGTH if input_has_class_token else input_seq_len + num_tok_output = num_patches + output_has_class_token = args.class_token_present + + # update input_param and load it to state_dict[key] + if input_has_class_token: + input_param_tok = input_param[:CLASS_TOKEN_LENGTH, :] + input_param_grid = input_param[CLASS_TOKEN_LENGTH:, :] + else: + input_param_tok = torch.zeros(CLASS_TOKEN_LENGTH, hidden_size) + input_param_grid = input_param + + assert input_param.shape[1] == hidden_size + + if num_tok_input != num_tok_output: + + gs_input = int(math.sqrt(num_tok_input)) + gs_new = (num_patches_per_dim_h, num_patches_per_dim_w) + + input_param_grid = input_param_grid.transpose(0, 1).contiguous() + input_param_grid = input_param_grid.reshape( + (1, -1, gs_input, gs_input) + ) + input_param_grid = input_param_grid.float() + scale_factor = (gs_new[0] / gs_input, gs_new[1] / gs_input) + + input_param_grid = F.interpolate( + input_param_grid, scale_factor=scale_factor, mode="bilinear" + ) + + input_param_grid = input_param_grid.half() + input_param_grid = input_param_grid.reshape((-1, num_tok_output)) + input_param_grid = input_param_grid.transpose(0, 1).contiguous() + + assert input_param_grid.shape[1] == hidden_size + + input_param = input_param_grid + assert ( + input_param.shape[0] == num_tok_output + and input_param.shape[1] == hidden_size + ) + + if output_has_class_token: + input_param = torch.cat((input_param_tok, input_param), dim=0) + + state_dict[key] = input_param + + +class VitBackbone(MegatronModule): + """Vision Transformer Model.""" + + def __init__(self, + config, + pre_process=True, + post_process=True, + class_token=True, + single_token_output=False, + post_layer_norm=True, + drop_path_rate=0.0): + super(VitBackbone, self).__init__(share_embeddings_and_output_weights=False) + args = get_args() + + self.fp16_lm_cross_entropy = args.fp16_lm_cross_entropy + + self.pre_process = pre_process + self.post_process = post_process + self.class_token = class_token + self.post_layer_norm = post_layer_norm + self.hidden_size = args.hidden_size + self.patch_dim = args.patch_dim + self.img_h = args.img_h + self.img_w = args.img_w + self.micro_batch_size = args.micro_batch_size + self.single_token_output = single_token_output + self.drop_path_rate = drop_path_rate + + assert self.img_h % self.patch_dim == 0 + assert self.img_w % self.patch_dim == 0 + self.num_patches_per_dim_h = self.img_h // self.patch_dim + self.num_patches_per_dim_w = self.img_w // self.patch_dim + self.num_patches = self.num_patches_per_dim_h * self.num_patches_per_dim_w + self.seq_length = self.num_patches + (CLASS_TOKEN_LENGTH if self.class_token else 0) + self.flatten_dim = self.patch_dim * self.patch_dim * args.num_channels + self.input_tensor = None + self.position_ids = None + + if self.pre_process: + # cls_token + if self.class_token: + self.cls_token = torch.nn.Parameter( + torch.randn(1, CLASS_TOKEN_LENGTH, self.hidden_size) + ) + torch.nn.init.zeros_(self.cls_token) + self.position_ids = torch.arange(self.seq_length).expand(1, -1).cuda() + + # Linear encoder + self.linear_encoder = torch.nn.Linear( + self.flatten_dim, self.hidden_size + ) + + # embedding + self.position_embeddings = torch.nn.Embedding( + self.seq_length, self.hidden_size + ) + init_method_normal(args.init_method_std)( + self.position_embeddings.weight + ) + + args.class_token_present = self.class_token + self.position_embeddings._register_load_state_dict_pre_hook( + twod_interpolate_position_embeddings_hook + ) + + self.embedding_dropout = torch.nn.Dropout(args.hidden_dropout) + + # Transformer + self.transformer = ParallelTransformer( + config, + pre_process=self.pre_process, + post_process=self.post_process, + post_layer_norm=self.post_layer_norm, + drop_path_rate=self.drop_path_rate + ) + + def set_input_tensor(self, input_tensor): + """See megatron.model.transformer.set_input_tensor()""" + self.transformer.set_input_tensor(input_tensor) + + def forward(self, input): + + if self.pre_process: + rearranged_input = einops.rearrange( + input, + "b c (h p1) (w p2) -> b (h w) (p1 p2 c)", + p1=self.patch_dim, + p2=self.patch_dim, + ) + + assert rearranged_input.dtype == torch.half + encoder_output = self.linear_encoder(rearranged_input) + + concatenated_tokens = encoder_output + if self.class_token: + cls_tokens = self.cls_token.expand(encoder_output.shape[0], -1, -1) + concatenated_tokens = torch.cat((cls_tokens, encoder_output), dim=1) + + token_embeddings = concatenated_tokens + \ + self.position_embeddings(self.position_ids[:, :concatenated_tokens.shape[1]]) + # [b, s, h] => [s, b, h] + token_embeddings = token_embeddings.transpose(0, 1).contiguous() + hidden_states = self.embedding_dropout(token_embeddings) + else: + hidden_states = input + + hidden_states = self.transformer(hidden_states, None) + + if self.post_process: + # [s b h] => [b s h] + if self.single_token_output: + hidden_states = hidden_states[0] + else: + hidden_states = hidden_states.transpose(0, 1).contiguous() + + return hidden_states + diff --git a/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/static/index.html b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/static/index.html new file mode 100644 index 0000000000000000000000000000000000000000..806287955bcc02e2d4148855af5ddb36ba94ae72 --- /dev/null +++ b/docker/intel_code/llama13b/Megatron-DeepSpeed/megatron/static/index.html @@ -0,0 +1,124 @@ + + + + + + + +Megatron + + + +
+

Prompt Megatron

+ + + + + +
+0 +/ 1000 +
+ +
+ + + + +