"src/lib/vscode:/vscode.git/clone" did not exist on "28ca6fb678c423446974fbf4662783715ddd7cb7"
Commit 8ddf66c6 authored by sunxx1's avatar sunxx1
Browse files

Merge branch 'hepj-test' into 'main'

修改README,增加训练脚本,完善模型转换代码

See merge request dcutoolkit/deeplearing/dlexamples_new!38
parents 0200794c bedf3c0c
#!/bin/bash
#export MIOPEN_DEBUG_DISABLE_FIND_DB=1
#export NCCL_SOCKET_IFNAME=ib0
#export HSA_USERPTR_FOR_PAGED_MEM=0
#export MIOPEN_DEBUG_DISABLE_FIND_DB=1
#export NCCL_SOCKET_IFNAME=eno1
export HSA_FORCE_FINE_GRAIN_PCIE=1
#source /public/software/apps/DeepLearning/PyTorch/pytorch-env.sh
export MIOPEN_FIND_MODE=1
#export MIOPEN_ENABLE_LOGGING_CMD=1
#export ROCBLAS_LAYER=3
module unload compiler/rocm/2.9
#export MIOPEN_DEBUG_CONV_DIRECT_ASM_3X3U=0
#export MIOPEN_DEBUG_CONV_DIRECT_ASM_WRW3X3=0
echo "MIOPEN_FIND_MODE=$MIOPEN_FIND_MODE"
#module load apps/PyTorch/1.5.0a0/hpcx-2.4.1-gcc-7.3.1-rocm3.3
#source /public/home/aiss/Pytorch/env_rocm3.3_torch1.5.sh
lrank=$OMPI_COMM_WORLD_LOCAL_RANK
comm_rank=$OMPI_COMM_WORLD_RANK
comm_size=$OMPI_COMM_WORLD_SIZE
#下边是修改的
#export HIP_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
#HSA_FORCE_FINE_GRAIN_PCIE=1 numactl --cpunodebind=4,5,6,7 --membind=4,5,6,7
#module load compiler/rocm/3.9.1
export PATH_PHRASE2=/public/software/apps/DeepLearning/Data/wikicorpus_en/lower_case_1_seq_len_512_max_pred_80_masked_lm_prob_0.15_random_seed_12345_dupe_factor_5_shard_1472_test_split_10/wikicorpus_en/training
APP="python3 run_pretraining_v1.py \
--input_dir=${PATH_PHRASE2} \
--output_dir=/public/home/hepj/outdir/torch/pre_wiki/phrase2/fp32 \
--config_file=/public/home/hepj/model_source/pytorch_bert/bert_config.json \
--bert_model=bert-large-uncased \
--train_batch_size=2 \
--max_seq_length=512 \
--max_predictions_per_seq=80 \
--max_steps=400000 \
--warmup_proportion=0128. \
--num_steps_per_checkpoint=20000 \
--learning_rate=4.0e-3 \
--seed=12439 \
--gradient_accumulation_steps=1 \
--allreduce_post_accumulation \
--do_train \
--phase2 \
--phase1_end_step=0 \
--gpus_per_node 1 \
--local_rank -1 \
--json-summary /public/home/hepj/outdir/torch/pre_wiki/phrase2/fp32/dllogger_dtk22.04.json
"
#--fp16 \
# --amp \
#--json-summary /public/home/hepj/out_dir/tourch/SQuAD/results.json
case ${lrank} in
[0])
export HIP_VISIBLE_DEVICES=0
export UCX_NET_DEVICES=mlx5_0:1
export UCX_IB_PCI_BW=mlx5_0:50Gbs
echo numactl --cpunodebind=0 --membind=0 ${APP}
numactl --cpunodebind=0 --membind=0 ${APP}
#echo GLOO_SOCKET_IFNAME=ib0 numactl --cpunodebind=0 --membind=0 ${APP}
#GLOO_SOCKET_IFNAME=ib0 numactl --cpunodebind=0 --membind=0 ${APP}
;;
[1])
export HIP_VISIBLE_DEVICES=1
export UCX_NET_DEVICES=mlx5_1:1
export UCX_IB_PCI_BW=mlx5_1:50Gbs
echo numactl --cpunodebind=1 --membind=1 ${APP}
numactl --cpunodebind=1 --membind=1 ${APP}
;;
[2])
export HIP_VISIBLE_DEVICES=2
export UCX_NET_DEVICES=mlx5_2:1
export UCX_IB_PCI_BW=mlx5_2:50Gbs
echo numactl --cpunodebind=2 --membind=2 ${APP}
numactl --cpunodebind=2 --membind=2 ${APP}
;;
[3])
export HIP_VISIBLE_DEVICES=3
export UCX_NET_DEVICES=mlx5_3:1
export UCX_IB_PCI_BW=mlx5_3:50Gbs
echo numactl --cpunodebind=3 --membind=3 ${APP}
numactl --cpunodebind=3 --membind=3 ${APP}
;;
esac
#!/bin/bash
export HSA_FORCE_FINE_GRAIN_PCIE=1
export MIOPEN_FIND_MODE=1
#export MIOPEN_ENABLE_LOGGING_CMD=1
#export ROCBLAS_LAYER=3
module unload compiler/rocm/2.9
echo "MIOPEN_FIND_MODE=$MIOPEN_FIND_MODE"
lrank=$OMPI_COMM_WORLD_LOCAL_RANK
comm_rank=$OMPI_COMM_WORLD_RANK
comm_size=$OMPI_COMM_WORLD_SIZE
#下边是修改的
export PATH_PHRASE2=/public/software/apps/DeepLearning/Data/wikicorpus_en/lower_case_1_seq_len_512_max_pred_80_masked_lm_prob_0.15_random_seed_12345_dupe_factor_5_shard_1472_test_split_10/wikicorpus_en/training
APP="python3 run_pretraining_v1.py \
--input_dir=${PATH_PHRASE2} \
--output_dir=/public/home/hepj/outdir/torch/pre_wiki/phrase2/fp16 \
--config_file=/public/home/hepj/model_source/pytorch_bert/bert_config.json \
--bert_model=bert-large-uncased \
--train_batch_size=2 \
--max_seq_length=512 \
--max_predictions_per_seq=80 \
--max_steps=400000 \
--warmup_proportion=0128. \
--num_steps_per_checkpoint=20000 \
--learning_rate=4.0e-3 \
--seed=12439 \
--gradient_accumulation_steps=1 \
--allreduce_post_accumulation \
--do_train \
--fp16 \
--amp \
--phase2 \
--phase1_end_step=0 \
--gpus_per_node 1 \
--local_rank -1 \
--json-summary /public/home/hepj/outdir/torch/pre_wiki/phrase2/fp16/dllogger_dtk22.04.json
"
#--json-summary /public/home/hepj/out_dir/tourch/SQuAD/results.json
case ${lrank} in
[0])
export HIP_VISIBLE_DEVICES=0
export UCX_NET_DEVICES=mlx5_0:1
export UCX_IB_PCI_BW=mlx5_0:50Gbs
echo numactl --cpunodebind=0 --membind=0 ${APP}
numactl --cpunodebind=0 --membind=0 ${APP}
#echo GLOO_SOCKET_IFNAME=ib0 numactl --cpunodebind=0 --membind=0 ${APP}
#GLOO_SOCKET_IFNAME=ib0 numactl --cpunodebind=0 --membind=0 ${APP}
;;
[1])
export HIP_VISIBLE_DEVICES=1
export UCX_NET_DEVICES=mlx5_1:1
export UCX_IB_PCI_BW=mlx5_1:50Gbs
echo numactl --cpunodebind=1 --membind=1 ${APP}
numactl --cpunodebind=1 --membind=1 ${APP}
;;
[2])
export HIP_VISIBLE_DEVICES=2
export UCX_NET_DEVICES=mlx5_2:1
export UCX_IB_PCI_BW=mlx5_2:50Gbs
echo numactl --cpunodebind=2 --membind=2 ${APP}
numactl --cpunodebind=2 --membind=2 ${APP}
;;
[3])
export HIP_VISIBLE_DEVICES=3
export UCX_NET_DEVICES=mlx5_3:1
export UCX_IB_PCI_BW=mlx5_3:50Gbs
echo numactl --cpunodebind=3 --membind=3 ${APP}
numactl --cpunodebind=3 --membind=3 ${APP}
;;
esac
#!/bin/bash
export HSA_FORCE_FINE_GRAIN_PCIE=1
export MIOPEN_FIND_MODE=1
module unload compiler/rocm/2.9
echo "MIOPEN_FIND_MODE=$MIOPEN_FIND_MODE"
lrank=$OMPI_COMM_WORLD_LOCAL_RANK
comm_rank=$OMPI_COMM_WORLD_RANK
comm_size=$OMPI_COMM_WORLD_SIZE
export HIP_VISIBLE_DEVICES=0,1,2,3
export PATH_PHRASE2=/public/software/apps/DeepLearning/Data/wikicorpus_en/lower_case_1_seq_len_512_max_pred_80_masked_lm_prob_0.15_random_seed_12345_dupe_factor_5_shard_1472_test_split_10/wikicorpus_en/training
APP="python3 run_pretraining_v4.py \
--input_dir=${PATH_PHRASE2} \
--output_dir=/public/home/hepj/outdir/tourch/pre_wiki4/phrase2/fp32 \
--config_file=/public/home/hepj/model_source/pytorch_bert/bert_config.json \
--bert_model=bert-large-uncased \
--train_batch_size=2 \
--max_seq_length=512 \
--max_predictions_per_seq=80 \
--max_steps=400000 \
--warmup_proportion=0128. \
--num_steps_per_checkpoint=200000 \
--learning_rate=4.0e-3 \
--seed=12439 \
--gradient_accumulation_steps=1 \
--allreduce_post_accumulation \
--do_train \
--phase2 \
--phase1_end_step 0 \
--local_rank ${comm_rank} \
--world_size 4 \
--gpus_per_node 1 \
--dist_url tcp://localhost:34567 \
--json-summary /public/home/hepj/outdir/torch/pre_wiki4/phrase2/fp32/dllogger.json
"
#--fp16 \
# --amp \
#--json-summary /public/home/hepj/out_dir/tourch/SQuAD/results.json
case ${lrank} in
[0])
export HIP_VISIBLE_DEVICES=0
export UCX_NET_DEVICES=mlx5_0:1
export UCX_IB_PCI_BW=mlx5_0:50Gbs
echo numactl --cpunodebind=0 --membind=0 ${APP}
numactl --cpunodebind=0 --membind=0 ${APP}
#echo GLOO_SOCKET_IFNAME=ib0 numactl --cpunodebind=0 --membind=0 ${APP}
#GLOO_SOCKET_IFNAME=ib0 numactl --cpunodebind=0 --membind=0 ${APP}
;;
[1])
export HIP_VISIBLE_DEVICES=1
export UCX_NET_DEVICES=mlx5_1:1
export UCX_IB_PCI_BW=mlx5_1:50Gbs
echo numactl --cpunodebind=1 --membind=1 ${APP}
numactl --cpunodebind=1 --membind=1 ${APP}
;;
[2])
export HIP_VISIBLE_DEVICES=2
export UCX_NET_DEVICES=mlx5_2:1
export UCX_IB_PCI_BW=mlx5_2:50Gbs
echo numactl --cpunodebind=2 --membind=2 ${APP}
numactl --cpunodebind=2 --membind=2 ${APP}
;;
[3])
export HIP_VISIBLE_DEVICES=3
export UCX_NET_DEVICES=mlx5_3:1
export UCX_IB_PCI_BW=mlx5_3:50Gbs
echo numactl --cpunodebind=3 --membind=3 ${APP}
numactl --cpunodebind=3 --membind=3 ${APP}
;;
esac
#!/bin/bash
export HSA_FORCE_FINE_GRAIN_PCIE=1
export MIOPEN_FIND_MODE=1
module unload compiler/rocm/2.9
echo "MIOPEN_FIND_MODE=$MIOPEN_FIND_MODE"
lrank=$OMPI_COMM_WORLD_LOCAL_RANK
comm_rank=$OMPI_COMM_WORLD_RANK
comm_size=$OMPI_COMM_WORLD_SIZE
#下边是修改的
export HIP_LAUNCH_BLOCKING=1
export HIP_VISIBLE_DEVICES=0,1,2,3
export PATH_PHRASE2=/public/software/apps/DeepLearning/Data/wikicorpus_en/lower_case_1_seq_len_512_max_pred_80_masked_lm_prob_0.15_random_seed_12345_dupe_factor_5_shard_1472_test_split_10/wikicorpus_en/training
APP="python3 run_pretraining_v4.py \
--input_dir=${PATH_PHRASE2} \
--output_dir=/public/home/hepj/outdir/tourch/pre_wiki4/phrase2/fp16 \
--config_file=/public/home/hepj/model_source/pytorch_bert/bert_config.json \
--bert_model=bert-large-uncased \
--train_batch_size=2 \
--max_seq_length=512 \
--max_predictions_per_seq=80 \
--max_steps=40000 \
--warmup_proportion=0128. \
--num_steps_per_checkpoint=10000 \
--learning_rate=4.0e-3 \
--seed=12439 \
--gradient_accumulation_steps=1 \
--allreduce_post_accumulation \
--do_train \
--phase2 \
--phase1_end_step 0 \
--local_rank ${comm_rank} \
--world_size 4 \
--gpus_per_node 1 \
--fp16 \
--amp \
--dist_url tcp://localhost:34567 \
--json-summary /public/home/hepj/outdir/torch/pre_wiki4/phrase2/fp16/dllogger.json
"
case ${lrank} in
[0])
export HIP_VISIBLE_DEVICES=0
export UCX_NET_DEVICES=mlx5_0:1
export UCX_IB_PCI_BW=mlx5_0:50Gbs
echo numactl --cpunodebind=0 --membind=0 ${APP}
numactl --cpunodebind=0 --membind=0 ${APP}
#echo GLOO_SOCKET_IFNAME=ib0 numactl --cpunodebind=0 --membind=0 ${APP}
#GLOO_SOCKET_IFNAME=ib0 numactl --cpunodebind=0 --membind=0 ${APP}
;;
[1])
export HIP_VISIBLE_DEVICES=1
export UCX_NET_DEVICES=mlx5_1:1
export UCX_IB_PCI_BW=mlx5_1:50Gbs
echo numactl --cpunodebind=1 --membind=1 ${APP}
numactl --cpunodebind=1 --membind=1 ${APP}
;;
[2])
export HIP_VISIBLE_DEVICES=2
export UCX_NET_DEVICES=mlx5_2:1
export UCX_IB_PCI_BW=mlx5_2:50Gbs
echo numactl --cpunodebind=2 --membind=2 ${APP}
numactl --cpunodebind=2 --membind=2 ${APP}
;;
[3])
export HIP_VISIBLE_DEVICES=3
export UCX_NET_DEVICES=mlx5_3:1
export UCX_IB_PCI_BW=mlx5_3:50Gbs
echo numactl --cpunodebind=3 --membind=3 ${APP}
numactl --cpunodebind=3 --membind=3 ${APP}
;;
esac
#!/bin/bash
#export MIOPEN_DEBUG_DISABLE_FIND_DB=1
#export NCCL_SOCKET_IFNAME=ib0
#export HSA_USERPTR_FOR_PAGED_MEM=0
#export MIOPEN_DEBUG_DISABLE_FIND_DB=1
#export NCCL_SOCKET_IFNAME=eno1
export HSA_FORCE_FINE_GRAIN_PCIE=1
#source /public/software/apps/DeepLearning/PyTorch/pytorch-env.sh
export MIOPEN_FIND_MODE=3
#export MIOPEN_ENABLE_LOGGING_CMD=1
#export ROCBLAS_LAYER=3
module unload compiler/rocm/2.9
#export MIOPEN_DEBUG_CONV_DIRECT_ASM_3X3U=0
#export MIOPEN_DEBUG_CONV_DIRECT_ASM_WRW3X3=0
echo "MIOPEN_FIND_MODE=$MIOPEN_FIND_MODE"
#module load apps/PyTorch/1.5.0a0/hpcx-2.4.1-gcc-7.3.1-rocm3.3
#source /public/home/aiss/Pytorch/env_rocm3.3_torch1.5.sh
lrank=$OMPI_COMM_WORLD_LOCAL_RANK
comm_rank=$OMPI_COMM_WORLD_RANK
comm_size=$OMPI_COMM_WORLD_SIZE
#module load compiler/rocm/3.9.1
APP="python3 run_squad_v1.py \
--train_file /public/home/hepj/data/sq1.1/train-v1.1.json \
--predict_file /public/home/hepj/data/sq1.1/dev-v1.1.json \
--init_checkpoint /public/home/hepj/model_source/pytorch_bert/model.ckpt-28252.pt \
--vocab_file /public/home/hepj/model_source/pytorch_bert/vocab.txt \
--output_dir /public/home/hepj/outdir/torch/SQuAD \
--config_file /public/home/hepj/model_source/pytorch_bert/bert_config.json \
--json-summary /public/home/hepj/outdir/torch/SQuAD/results.json \
--bert_model bert-large-uncased \
--do_train \
--do_predict \
--train_batch_size 4 \
--predict_batch_size 4 \
--gpus_per_node 1 \
--local_rank -1 \
--eval_script /public/home/hepj/squad_eval/evaluate-v1.1.py
"
#--json-summary /public/home/hepj/out_dir/tourch/SQuAD/results.json
case ${lrank} in
[0])
export HIP_VISIBLE_DEVICES=0
export UCX_NET_DEVICES=mlx5_0:1
export UCX_IB_PCI_BW=mlx5_0:50Gbs
echo numactl --cpunodebind=0 --membind=0 ${APP}
numactl --cpunodebind=0 --membind=0 ${APP}
#echo GLOO_SOCKET_IFNAME=ib0 numactl --cpunodebind=0 --membind=0 ${APP}
#GLOO_SOCKET_IFNAME=ib0 numactl --cpunodebind=0 --membind=0 ${APP}
;;
[1])
export HIP_VISIBLE_DEVICES=1
export UCX_NET_DEVICES=mlx5_1:1
export UCX_IB_PCI_BW=mlx5_1:50Gbs
echo numactl --cpunodebind=1 --membind=1 ${APP}
numactl --cpunodebind=1 --membind=1 ${APP}
;;
[2])
export HIP_VISIBLE_DEVICES=2
export UCX_NET_DEVICES=mlx5_2:1
export UCX_IB_PCI_BW=mlx5_2:50Gbs
echo numactl --cpunodebind=2 --membind=2 ${APP}
numactl --cpunodebind=2 --membind=2 ${APP}
;;
[3])
export HIP_VISIBLE_DEVICES=3
export UCX_NET_DEVICES=mlx5_3:1
export UCX_IB_PCI_BW=mlx5_3:50Gbs
echo numactl --cpunodebind=3 --membind=3 ${APP}
numactl --cpunodebind=3 --membind=3 ${APP}
;;
esac
#!/bin/bash
#export MIOPEN_DEBUG_DISABLE_FIND_DB=1
#export NCCL_SOCKET_IFNAME=ib0
#export HSA_USERPTR_FOR_PAGED_MEM=0
#export MIOPEN_DEBUG_DISABLE_FIND_DB=1
#export NCCL_SOCKET_IFNAME=eno1
export HSA_FORCE_FINE_GRAIN_PCIE=1
#source /public/software/apps/DeepLearning/PyTorch/pytorch-env.sh
export MIOPEN_FIND_MODE=3
#export MIOPEN_ENABLE_LOGGING_CMD=1
#export export ROCBLAS_LAYER=3
module unload compiler/rocm/2.9
#export MIOPEN_DEBUG_CONV_DIRECT_ASM_3X3U=0
#export MIOPEN_DEBUG_CONV_DIRECT_ASM_WRW3X3=0
echo "MIOPEN_FIND_MODE=$MIOPEN_FIND_MODE"
#module load apps/PyTorch/1.5.0a0/hpcx-2.4.1-gcc-7.3.1-rocm3.3
#source /public/home/aiss/Pytorch/env_rocm3.3_torch1.5.sh
lrank=$OMPI_COMM_WORLD_LOCAL_RANK
comm_rank=$OMPI_COMM_WORLD_RANK
comm_size=$OMPI_COMM_WORLD_SIZE
#下边是修改的
export HIP_VISIBLE_DEVICES=0,1,2,3
#HSA_FORCE_FINE_GRAIN_PCIE=1 numactl --cpunodebind=4,5,6,7 --membind=4,5,6,7
#module load compiler/rocm/3.9.1
APP="python3 run_squad_v4.py \
--train_file /public/home/hepj/data/sq1.1/train-v1.1.json \
--predict_file /public/home/hepj/data/sq1.1/dev-v1.1.json \
--init_checkpoint /public/home/hepj/model_source/pytorch_bert/model.ckpt-28252.pt \
--vocab_file /public/home/hepj/model_source/pytorch_bert/vocab.txt \
--output_dir /public/home/hepj/outdir/torch/SQuAD4 \
--config_file /public/home/hepj/model_source/pytorch_bert/bert_config.json \
--json-summary /public/home/hepj/outdir/torch/SQuAD4/results.json \
--bert_model bert-large-uncased \
--do_train \
--do_predict \
--do_eval \
--train_batch_size 4 \
--predict_batch_size 4 \
--gpus_per_node 1 \
--local_rank ${comm_rank} \
--world_size 4 \
--use_env \
--dist_url tcp://localhost:34567 \
--eval_script /public/home/hepj/squad_eval/evaluate-v1.1.py
"
# --fp16 \
# --amp \
case ${lrank} in
[0])
export HIP_VISIBLE_DEVICES=0
export UCX_NET_DEVICES=mlx5_0:1
export UCX_IB_PCI_BW=mlx5_0:50Gbs
echo numactl --cpunodebind=0 --membind=0 ${APP}
numactl --cpunodebind=0 --membind=0 ${APP}
#echo GLOO_SOCKET_IFNAME=ib0 numactl --cpunodebind=0 --membind=0 ${APP}
#GLOO_SOCKET_IFNAME=ib0 numactl --cpunodebind=0 --membind=0 ${APP}
;;
[1])
export HIP_VISIBLE_DEVICES=1
export UCX_NET_DEVICES=mlx5_1:1
export UCX_IB_PCI_BW=mlx5_1:50Gbs
echo numactl --cpunodebind=1 --membind=1 ${APP}
numactl --cpunodebind=1 --membind=1 ${APP}
;;
[2])
export HIP_VISIBLE_DEVICES=2
export UCX_NET_DEVICES=mlx5_2:1
export UCX_IB_PCI_BW=mlx5_2:50Gbs
echo numactl --cpunodebind=2 --membind=2 ${APP}
numactl --cpunodebind=2 --membind=2 ${APP}
;;
[3])
export HIP_VISIBLE_DEVICES=3
export UCX_NET_DEVICES=mlx5_3:1
export UCX_IB_PCI_BW=mlx5_3:50Gbs
echo numactl --cpunodebind=3 --membind=3 ${APP}
numactl --cpunodebind=3 --membind=3 ${APP}
;;
esac
#!/bin/bash
#export MIOPEN_DEBUG_DISABLE_FIND_DB=1
#export NCCL_SOCKET_IFNAME=ib0
#export HSA_USERPTR_FOR_PAGED_MEM=0
#export MIOPEN_DEBUG_DISABLE_FIND_DB=1
#export NCCL_SOCKET_IFNAME=eno1
export HSA_FORCE_FINE_GRAIN_PCIE=1
#source /public/software/apps/DeepLearning/PyTorch/pytorch-env.sh
export MIOPEN_FIND_MODE=3
#export MIOPEN_ENABLE_LOGGING_CMD=1
#export export ROCBLAS_LAYER=3
module unload compiler/rocm/2.9
#export MIOPEN_DEBUG_CONV_DIRECT_ASM_3X3U=0
#export MIOPEN_DEBUG_CONV_DIRECT_ASM_WRW3X3=0
echo "MIOPEN_FIND_MODE=$MIOPEN_FIND_MODE"
#module load apps/PyTorch/1.5.0a0/hpcx-2.4.1-gcc-7.3.1-rocm3.3
#source /public/home/aiss/Pytorch/env_rocm3.3_torch1.5.sh
lrank=$OMPI_COMM_WORLD_LOCAL_RANK
comm_rank=$OMPI_COMM_WORLD_RANK
comm_size=$OMPI_COMM_WORLD_SIZE
#下边是修改的
export HIP_VISIBLE_DEVICES=0,1,2,3
#HSA_FORCE_FINE_GRAIN_PCIE=1 numactl --cpunodebind=4,5,6,7 --membind=4,5,6,7
#module load compiler/rocm/3.9.1
APP="python3 run_squad_v4.py \
--train_file /public/home/hepj/data/sq1.1/train-v1.1.json \
--predict_file /public/home/hepj/data/sq1.1/dev-v1.1.json \
--init_checkpoint /public/home/hepj/model_source/pytorch_bert/model.ckpt-28252.pt \
--vocab_file /public/home/hepj/model_source/pytorch_bert/vocab.txt \
--output_dir /public/home/hepj/outdir/torch/SQuAD4 \
--config_file /public/home/hepj/model_source/pytorch_bert/bert_config.json \
--json-summary /public/home/hepj/outdir/torch/SQuAD4/results.json \
--bert_model bert-large-uncased \
--do_train \
--do_predict \
--do_eval \
--train_batch_size 4 \
--predict_batch_size 4 \
--gpus_per_node 1 \
--local_rank ${comm_rank} \
--world_size 4 \
--use_env \
--fp16 \
--amp \
--dist_url tcp://localhost:34567 \
--eval_script /public/home/hepj/squad_eval/evaluate-v1.1.py
"
case ${lrank} in
[0])
export HIP_VISIBLE_DEVICES=0
export UCX_NET_DEVICES=mlx5_0:1
export UCX_IB_PCI_BW=mlx5_0:50Gbs
echo numactl --cpunodebind=0 --membind=0 ${APP}
numactl --cpunodebind=0 --membind=0 ${APP}
#echo GLOO_SOCKET_IFNAME=ib0 numactl --cpunodebind=0 --membind=0 ${APP}
#GLOO_SOCKET_IFNAME=ib0 numactl --cpunodebind=0 --membind=0 ${APP}
;;
[1])
export HIP_VISIBLE_DEVICES=1
export UCX_NET_DEVICES=mlx5_1:1
export UCX_IB_PCI_BW=mlx5_1:50Gbs
echo numactl --cpunodebind=1 --membind=1 ${APP}
numactl --cpunodebind=1 --membind=1 ${APP}
;;
[2])
export HIP_VISIBLE_DEVICES=2
export UCX_NET_DEVICES=mlx5_2:1
export UCX_IB_PCI_BW=mlx5_2:50Gbs
echo numactl --cpunodebind=2 --membind=2 ${APP}
numactl --cpunodebind=2 --membind=2 ${APP}
;;
[3])
export HIP_VISIBLE_DEVICES=3
export UCX_NET_DEVICES=mlx5_3:1
export UCX_IB_PCI_BW=mlx5_3:50Gbs
echo numactl --cpunodebind=3 --membind=3 ${APP}
numactl --cpunodebind=3 --membind=3 ${APP}
;;
esac
#!/bin/bash
#export MIOPEN_DEBUG_DISABLE_FIND_DB=1
#export NCCL_SOCKET_IFNAME=ib0
#export HSA_USERPTR_FOR_PAGED_MEM=0
#export MIOPEN_DEBUG_DISABLE_FIND_DB=1
#export NCCL_SOCKET_IFNAME=eno1
export HSA_FORCE_FINE_GRAIN_PCIE=1
#source /public/software/apps/DeepLearning/PyTorch/pytorch-env.sh
export MIOPEN_FIND_MODE=3
#export MIOPEN_ENABLE_LOGGING_CMD=1
#export ROCBLAS_LAYER=3
module unload compiler/rocm/2.9
#export MIOPEN_DEBUG_CONV_DIRECT_ASM_3X3U=0
#export MIOPEN_DEBUG_CONV_DIRECT_ASM_WRW3X3=0
echo "MIOPEN_FIND_MODE=$MIOPEN_FIND_MODE"
#module load apps/PyTorch/1.5.0a0/hpcx-2.4.1-gcc-7.3.1-rocm3.3
#source /public/home/aiss/Pytorch/env_rocm3.3_torch1.5.sh
lrank=$OMPI_COMM_WORLD_LOCAL_RANK
comm_rank=$OMPI_COMM_WORLD_RANK
comm_size=$OMPI_COMM_WORLD_SIZE
#下边是修改的
#export HIP_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
#HSA_FORCE_FINE_GRAIN_PCIE=1 numactl --cpunodebind=4,5,6,7 --membind=4,5,6,7
#module load compiler/rocm/3.9.1
APP="python3 run_squad_v1.py \
--train_file /public/home/hepj/model/model_source/sq1.1/train-v1.1.json \
--predict_file /public/home/hepj/model/model_source/sq1.1/dev-v1.1.json \
--init_checkpoint /public/home/hepj/model/model_source/pytorch_bert/model.ckpt-28252.pt \
--vocab_file /public/home/hepj/model/model_source/pytorch_bert/vocab.txt \
--output_dir /public/home/hepj/outdir/tourch/SQuAD \
--config_file /public/home/hepj/model/model_source/pytorch_bert/bert_config.json \
--json-summary /public/home/hepj/outdir/torch/SQuAD/results.json \
--bert_model bert-large-uncased \
--do_train \
--do_predict \
--do_eval \
--train_batch_size 4 \
--predict_batch_size 4 \
--gpus_per_node 1 \
--local_rank -1 \
--fp16 \
--amp \
--eval_script /public/home/hepj/squad_eval/evaluate-v1.1.py
"
#--json-summary /public/home/hepj/out_dir/tourch/SQuAD/results.json
case ${lrank} in
[0])
export HIP_VISIBLE_DEVICES=0
export UCX_NET_DEVICES=mlx5_0:1
export UCX_IB_PCI_BW=mlx5_0:50Gbs
echo numactl --cpunodebind=0 --membind=0 ${APP}
numactl --cpunodebind=0 --membind=0 ${APP}
#echo GLOO_SOCKET_IFNAME=ib0 numactl --cpunodebind=0 --membind=0 ${APP}
#GLOO_SOCKET_IFNAME=ib0 numactl --cpunodebind=0 --membind=0 ${APP}
;;
[1])
export HIP_VISIBLE_DEVICES=1
export UCX_NET_DEVICES=mlx5_1:1
export UCX_IB_PCI_BW=mlx5_1:50Gbs
echo numactl --cpunodebind=1 --membind=1 ${APP}
numactl --cpunodebind=1 --membind=1 ${APP}
;;
[2])
export HIP_VISIBLE_DEVICES=2
export UCX_NET_DEVICES=mlx5_2:1
export UCX_IB_PCI_BW=mlx5_2:50Gbs
echo numactl --cpunodebind=2 --membind=2 ${APP}
numactl --cpunodebind=2 --membind=2 ${APP}
;;
[3])
export HIP_VISIBLE_DEVICES=3
export UCX_NET_DEVICES=mlx5_3:1
export UCX_IB_PCI_BW=mlx5_3:50Gbs
echo numactl --cpunodebind=3 --membind=3 ${APP}
numactl --cpunodebind=3 --membind=3 ${APP}
;;
esac
# Copyright (c) 2019-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.
ARG FROM_IMAGE_NAME=nvcr.io/nvidia/pytorch:20.06-py3
FROM ${FROM_IMAGE_NAME}
# Install dependencies
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
bzip2 \
cabextract \
iputils-ping \
pbzip2 \
pv \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /workspace/bert
COPY requirements.txt .
RUN pip install --no-cache-dir https://github.com/mlperf/logging/archive/9ea0afa.zip \
&& pip install --no-cache-dir -r requirements.txt
# Preprocessing
#WORKDIR /workspace
#RUN git clone https://github.com/attardi/wikiextractor.git
# Install BERT
ENV BERT_PREP_WORKING_DIR /workspace/bert/data
WORKDIR /workspace/bert
COPY . .
RUN cd /workspace/bert/mhalib && python setup.py build && cp build/lib*/mhalib* ../
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
\ No newline at end of file
BERT PyTorch
This repository includes software from https://github.com/huggingface/pytorch-pretrained-BERT
licensed under the Apache License 2.0.
# Location of the input files
This [GCS location](https://console.cloud.google.com/storage/browser/pkanwar-bert) contains the following.
* TensorFlow checkpoint (bert_model.ckpt) containing the pre-trained weights (which is actually 3 files).
* Vocab file (vocab.txt) to map WordPiece to word id.
* Config file (bert_config.json) which specifies the hyperparameters of the model.
# Download and preprocess datasets
Download the [wikipedia dump](https://dumps.wikimedia.org/enwiki/20200101/enwiki-20200101-pages-articles-multistream.xml.bz2) and extract the pages
The wikipedia dump can be downloaded from this link in this directory, and should contain the following file:
enwiki-20200101-pages-articles-multistream.xml.bz2
Run [WikiExtractor.py](https://github.com/attardi/wikiextractor) to extract the wiki pages from the XML
The generated wiki pages file will be stored as <data dir>/LL/wiki_nn; for example <data dir>/AA/wiki_00. Each file is ~1MB, and each sub directory has 100 files from wiki_00 to wiki_99, except the last sub directory. For the 20200101 dump, the last file is FE/wiki_17.
Clean up
The clean up scripts (some references here) are in the scripts directory.
The following command will run the clean up steps, and put the results in ./results
./process_wiki.sh '<data dir>/*/wiki_??'
```shell
cd cleanup_scripts
mkdir -p wiki
cd wiki
wget https://dumps.wikimedia.org/enwiki/20200101/enwiki-20200101-pages-articles-multistream.xml.bz2 # Optionally use curl instead
bzip2 -d enwiki-20200101-pages-articles-multistream.xml.bz2
cd .. # back to bert/cleanup_scripts
git clone https://github.com/attardi/wikiextractor.git
python3 wikiextractor/WikiExtractor.py wiki/enwiki-20200101-pages-articles-multistream.xml # Results are placed in bert/cleanup_scripts/text
./process_wiki.sh '<text/*/wiki_??'
```
After running the process_wiki.sh script, for the 20200101 wiki dump, there will be 500 files, named part-00xxx-of-00500 in the ./results directory.
# Checkpoint conversion
python convert_tf_checkpoint.py --tf_checkpoint /cks/model.ckpt-28252 --bert_config_path /cks/bert_config.json --output_checkpoint model.ckpt-28252.pt
# Generate the BERT input dataset
The create_pretraining_data.py script duplicates the input plain text, replaces different sets of words with masks for each duplication, and serializes the output into the TFRecord file format.
```shell
python3 create_pretraining_data.py \
--input_file=<path to ./results of previous step>/part-XX-of-00500 \
--output_file=<tfrecord dir>/part-XX-of-00500 \
--vocab_file=<path to vocab.txt> \
--do_lower_case=True \
--max_seq_length=512 \
--max_predictions_per_seq=76 \
--masked_lm_prob=0.15 \
--random_seed=12345 \
--dupe_factor=10
```
The generated tfrecord has 500 parts, totalling to ~365GB.
# Running the model
Building the Docker container
```shell
docker build --pull -t <docker/registry>/mlperf-nvidia:language_model .
docker push <docker/registry>/mlperf-nvidia:language_model
```
To run this model, use the following command. Replace the configuration script to match the system being used (e.g., config_DGX1.sh, config_DGX2.sh, config_DGXA100.sh).
```shell
source config_DGXA100.sh
sbatch -N${DGXNNODES} --ntasks-per-node=${DGXNGPU} --time=${WALLTIME} run.sub
```
Alternative launch with nvidia-docker. Replace the configuration script to match the system being used (e.g., config_DGX1.sh, config_DGX2.sh, config_DGXA100.sh).
```bash
docker build --pull -t mlperf-nvidia:language_model .
source config_DGXA100.sh
CONT=mlperf-nvidia:language_model DATADIR=<path/to/datadir> DATADIR_PHASE2=<path/to/datadir_phase2> EVALDIR=<path/to/evaldir> CHECKPOINTDIR=<path/to/checkpointdir> CHECKPOINTDIR_PHASE1=<path/to/checkpointdir_phase1> ./run_with_docker.sh
```
For multi-node training, we use Slurm for scheduling and Pyxis to run our container.
## Configuration File Naming Convention
All configuration files follow the format `config_<SYSTEM_NAME>_<NODES>x<GPUS/NODE>x<BATCH/GPU>x<GRADIENT_ACCUMULATION_STEPS>.sh`.
### Example 1
A DGX1 system with 1 node, 8 GPUs per node, batch size of 6 per GPU, and 6 gradient accumulation steps would use `config_DGX1_1x8x6x6.sh`.
### Example 2
A DGX A100 system with 32 nodes, 8 GPUs per node, batch size of 20 per GPU, and no gradient accumulation would use `config_DGXA100_32x8x20x1.sh`
# Acknowledgements
We'd like to thank members of the ONNX Runtime team at Microsoft for their suggested performance optimization to reduce the size of the last linear layer to only output the fraction of tokens that participate in the MLM loss calculation.
#! /bin/bash
set -euo pipefail
print_usage() {
cat << EOF
${0} [options] [--] COMMAND [ARG...]
Control binding policy for each task. Assumes one rank will be launched for each GPU.
Options:
--cpu=MODE
* exclusive -- bind each rank to an exclusive set of cores near its GPU
* exclusive,nosmt -- bind each rank to an exclusive set of cores near its GPU, without hyperthreading
* node -- bind each rank to all cores in the NUMA node nearest its GPU [default]
* *.sh -- bind each rank using the bash associative array bind_cpu_cores or bind_cpu_nodes from a file
* off -- don't bind
--mem=MODE
* node -- bind each rank to the nearest NUMA node [default]
* *.sh -- bind each rank using the bash associative array bind_mem from a file
* off -- don't bind
--ib=MODE
* single -- bind each rank to a single IB device near its GPU
* off -- don't bind [default]
--cluster=CLUSTER
Select which cluster is being used. May be required if system params cannot be detected.
EOF
}
################################################################################
# Argument parsing
################################################################################
cpu_mode='node'
mem_mode='node'
ib_mode='off'
cluster=''
while [ $# -gt 0 ]; do
case "$1" in
-h|--help) print_usage ; exit 0 ;;
--cpu=*) cpu_mode="${1/*=/}"; shift ;;
--cpu) cpu_mode="$2"; shift 2 ;;
--mem=*) mem_mode="${1/*=/}"; shift ;;
--mem) mem_mode="$2"; shift 2 ;;
--ib=*) ib_mode="${1/*=/}"; shift ;;
--ib) ib_mode="$2"; shift 2 ;;
--cluster=*) cluster="${1/*=/}"; shift ;;
--cluster) cluster="$2"; shift 2 ;;
--) shift; break ;;
*) break ;;
esac
done
if [ $# -lt 1 ]; then
echo 'ERROR: no command given' 2>&1
print_usage
exit 1
fi
################################################################################
# Get system params
################################################################################
# LOCAL_RANK is set with an enroot hook for Pytorch containers
# SLURM_LOCALID is set by Slurm
# OMPI_COMM_WORLD_LOCAL_RANK is set by mpirun
readonly local_rank="${LOCAL_RANK:=${SLURM_LOCALID:=${OMPI_COMM_WORLD_LOCAL_RANK:-}}}"
if [ -z "${local_rank}" ]; then
echo 'ERROR: cannot read LOCAL_RANK from env' >&2
exit 1
fi
num_gpus=$(nvidia-smi -i 0 --query-gpu=count --format=csv,noheader,nounits)
if [ "${local_rank}" -ge "${num_gpus}" ]; then
echo "ERROR: local rank is ${local_rank}, but there are only ${num_gpus} gpus available" >&2
exit 1
fi
get_lscpu_value() {
awk -F: "(\$1 == \"${1}\"){gsub(/ /, \"\", \$2); print \$2; found=1} END{exit found!=1}"
}
lscpu_out=$(lscpu)
num_sockets=$(get_lscpu_value 'Socket(s)' <<< "${lscpu_out}")
num_nodes=$(get_lscpu_value 'NUMA node(s)' <<< "${lscpu_out}")
cores_per_socket=$(get_lscpu_value 'Core(s) per socket' <<< "${lscpu_out}")
echo "num_sockets = ${num_sockets} num_nodes=${num_nodes} cores_per_socket=${cores_per_socket}"
readonly cores_per_node=$(( (num_sockets * cores_per_socket) / num_nodes ))
if [ ${num_gpus} -gt 1 ]; then
readonly gpus_per_node=$(( num_gpus / num_nodes ))
else
readonly gpus_per_node=1
fi
readonly cores_per_gpu=$(( cores_per_node / gpus_per_node ))
readonly local_node=$(( local_rank / gpus_per_node ))
declare -a ibdevs=()
case "${cluster}" in
circe)
# Need to specialize for circe because IB detection is hard
ibdevs=(mlx5_1 mlx5_2 mlx5_3 mlx5_4 mlx5_7 mlx5_8 mlx5_9 mlx5_10)
;;
selene)
# Need to specialize for selene because IB detection is hard
ibdevs=(mlx5_0 mlx5_1 mlx5_2 mlx5_3 mlx5_6 mlx5_7 mlx5_8 mlx5_9)
;;
'')
if ibstat_out="$(ibstat -l 2>/dev/null | sort -V)" ; then
mapfile -t ibdevs <<< "${ibstat_out}"
fi
;;
*)
echo "ERROR: Unknown cluster '${cluster}'" >&2
exit 1
;;
esac
readonly num_ibdevs="${#ibdevs[@]}"
################################################################################
# Setup for exec
################################################################################
declare -a numactl_args=()
case "${cpu_mode}" in
exclusive)
numactl_args+=( "$(printf -- "--physcpubind=%u-%u,%u-%u" \
$(( local_rank * cores_per_gpu )) \
$(( (local_rank + 1) * cores_per_gpu - 1 )) \
$(( local_rank * cores_per_gpu + (cores_per_gpu * gpus_per_node * num_nodes) )) \
$(( (local_rank + 1) * cores_per_gpu + (cores_per_gpu * gpus_per_node * num_nodes) - 1 )) \
)" )
;;
exclusive,nosmt)
numactl_args+=( "$(printf -- "--physcpubind=%u-%u" \
$(( local_rank * cores_per_gpu )) \
$(( (local_rank + 1) * cores_per_gpu - 1 )) \
)" )
;;
node)
numactl_args+=( "--cpunodebind=${local_node}" )
;;
*.sh)
source "${cpu_mode}"
if [ -n "${bind_cpu_cores:-}" ]; then
numactl_args+=( "--physcpubind=${bind_cpu_cores[${local_rank}]}" )
elif [ -n "${bind_cpu_nodes:-}" ]; then
numactl_args+=( "--cpunodebind=${bind_cpu_nodes[${local_rank}]}" )
else
echo "ERROR: invalid CPU affinity file ${cpu_mode}." >&2
exit 1
fi
;;
off|'')
;;
*)
echo "ERROR: invalid cpu mode '${cpu_mode}'" 2>&1
print_usage
exit 1
;;
esac
case "${mem_mode}" in
node)
numactl_args+=( "--membind=${local_node}" )
;;
*.sh)
source "${mem_mode}"
if [ -z "${bind_mem:-}" ]; then
echo "ERROR: invalid memory affinity file ${mem_mode}." >&2
exit 1
fi
numactl_args+=( "--membind=${bind_mem[${local_rank}]}" )
;;
off|'')
;;
*)
echo "ERROR: invalid mem mode '${mem_mode}'" 2>&1
print_usage
exit 1
;;
esac
case "${ib_mode}" in
single)
if [ "${num_ibdevs}" -eq 0 ]; then
echo "WARNING: used '$0 --ib=single', but there are 0 IB devices available; skipping IB binding." 2>&1
else
readonly ibdev="${ibdevs[$(( local_rank * num_ibdevs / num_gpus ))]}"
export OMPI_MCA_btl_openib_if_include="${OMPI_MCA_btl_openib_if_include-$ibdev}"
export UCX_NET_DEVICES="${UCX_NET_DEVICES-$ibdev:1}"
fi
;;
off|'')
;;
*)
echo "ERROR: invalid ib mode '${ib_mode}'" 2>&1
print_usage
exit 1
;;
esac
################################################################################
# Exec
################################################################################
if [ "${#numactl_args[@]}" -gt 0 ] ; then
set -x
exec numactl "${numactl_args[@]}" -- "${@}"
else
exec "${@}"
fi
# Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import subprocess
import os
import socket
from argparse import ArgumentParser, REMAINDER
import torch
def parse_args():
"""
Helper function parsing the command line options
@retval ArgumentParser
"""
parser = ArgumentParser(description="PyTorch distributed training launch "
"helper utilty that will spawn up "
"multiple distributed processes")
# Optional arguments for the launch helper
parser.add_argument("--nnodes", type=int, default=1,
help="The number of nodes to use for distributed "
"training")
parser.add_argument("--node_rank", type=int, default=0,
help="The rank of the node for multi-node distributed "
"training")
parser.add_argument("--nproc_per_node", type=int, default=1,
help="The number of processes to launch on each node, "
"for GPU training, this is recommended to be set "
"to the number of GPUs in your system so that "
"each process can be bound to a single GPU.")
parser.add_argument("--master_addr", default="127.0.0.1", type=str,
help="Master node (rank 0)'s address, should be either "
"the IP address or the hostname of node 0, for "
"single node multi-proc training, the "
"--master_addr can simply be 127.0.0.1")
parser.add_argument("--master_port", default=29500, type=int,
help="Master node (rank 0)'s free port that needs to "
"be used for communciation during distributed "
"training")
parser.add_argument('--no_hyperthreads', action='store_true',
help='Flag to disable binding to hyperthreads')
parser.add_argument('--no_membind', action='store_true',
help='Flag to disable memory binding')
# non-optional arguments for binding
parser.add_argument("--nsockets_per_node", type=int, required=True,
help="Number of CPU sockets on a node")
parser.add_argument("--ncores_per_socket", type=int, required=True,
help="Number of CPU cores per socket")
# positional
parser.add_argument("training_script", type=str,
help="The full path to the single GPU training "
"program/script to be launched in parallel, "
"followed by all the arguments for the "
"training script")
# rest from the training program
parser.add_argument('training_script_args', nargs=REMAINDER)
return parser.parse_args()
def main():
args = parse_args()
# variables for numactrl binding
NSOCKETS = args.nsockets_per_node
NGPUS_PER_SOCKET = (args.nproc_per_node // args.nsockets_per_node) + (1 if (args.nproc_per_node % args.nsockets_per_node) else 0)
NCORES_PER_GPU = args.ncores_per_socket // NGPUS_PER_SOCKET
# world size in terms of number of processes
dist_world_size = args.nproc_per_node * args.nnodes
# set PyTorch distributed related environmental variables
current_env = os.environ.copy()
current_env["MASTER_ADDR"] = args.master_addr
current_env["MASTER_PORT"] = str(args.master_port)
current_env["WORLD_SIZE"] = str(dist_world_size)
processes = []
for local_rank in range(0, args.nproc_per_node):
# each process's rank
dist_rank = args.nproc_per_node * args.node_rank + local_rank
current_env["RANK"] = str(dist_rank)
# form numactrl binding command
cpu_ranges = [local_rank * NCORES_PER_GPU,
(local_rank + 1) * NCORES_PER_GPU - 1,
local_rank * NCORES_PER_GPU + (NCORES_PER_GPU * NGPUS_PER_SOCKET * NSOCKETS),
(local_rank + 1) * NCORES_PER_GPU + (NCORES_PER_GPU * NGPUS_PER_SOCKET * NSOCKETS) - 1]
numactlargs = []
if args.no_hyperthreads:
numactlargs += [ "--physcpubind={}-{}".format(*cpu_ranges[0:2]) ]
else:
numactlargs += [ "--physcpubind={}-{},{}-{}".format(*cpu_ranges) ]
if not args.no_membind:
memnode = local_rank // NGPUS_PER_SOCKET
numactlargs += [ "--membind={}".format(memnode) ]
# spawn the processes
cmd = [ "/usr/bin/numactl" ] \
+ numactlargs \
+ [ sys.executable,
"-u",
args.training_script,
"--local_rank={}".format(local_rank)
] \
+ args.training_script_args
process = subprocess.Popen(cmd, env=current_env)
processes.append(process)
for process in processes:
process.wait()
if __name__ == "__main__":
main()
import torch
import mhalib
###########################################################################################
class Bmm1Function(torch.autograd.Function):
@staticmethod
def forward(ctx, batch1, batch2, seqlen, batch, maxseqlen, heads, embed, scale, stream, sync):
ctx.save_for_backward(batch1, batch2, seqlen)
ctx.batch = batch
ctx.maxseqlen = maxseqlen
ctx.heads = heads
ctx.embed = embed
ctx.scale = scale
ctx.sync = sync
ctx.stream = stream
ntokens = seqlen.sum().item()
ctx.ntokens = ntokens
ntokens2 = 0
for i in range(batch):
ntokens2 += seqlen[i]*seqlen[i]
output = torch.empty(ntokens2*heads, device="cuda", dtype=torch.float16)
mhalib.FastBmm1Fprop(batch2.flatten().contiguous(), batch1.flatten().contiguous(), output.flatten().contiguous(), batch, seqlen, heads, embed, scale, False, stream, sync)
return output[:ntokens2*heads]
@staticmethod
def backward(ctx, grad_output):
batch1, batch2, seqlen = ctx.saved_tensors
batch = ctx.batch
maxseqlen = ctx.maxseqlen
heads = ctx.heads
embed = ctx.embed
ntokens = ctx.ntokens
grad_batch1 = torch.empty(ntokens,heads*embed, device="cuda", dtype=torch.float16)
grad_batch2 = torch.empty(ntokens,heads*embed, device="cuda", dtype=torch.float16)
mhalib.FastBmm1Dgrad2(batch2.flatten().contiguous(), grad_output.flatten().contiguous(), grad_batch1.flatten().contiguous(), batch, seqlen, heads, embed, ctx.scale, False, ctx.stream, ctx.sync)
mhalib.FastBmm1Dgrad1(batch1.flatten().contiguous(), grad_output.flatten().contiguous(), grad_batch2.flatten().contiguous(), batch, seqlen, heads, embed, ctx.scale, False, ctx.stream, ctx.sync)
return grad_batch1[:ntokens], grad_batch2[:ntokens], None, None, None, None, None, None, None, None
class Bmm1(torch.nn.Module):
def __init__(self, batch, seqlen, heads, embed, scale=False, stream=True, sync=True):
super(Bmm1, self).__init__()
self.heads = heads
self.embed = embed
self.maxseqlen = seqlen
self.scale = scale
self.sync = sync
self.stream = stream
def forward(self, batch1, batch2, batch, seqlen):
return Bmm1Function.apply(batch1, batch2, seqlen, batch, self.maxseqlen, self.heads, self.embed, self.scale, self.stream, self.sync)
##########################################################################################
class Bmm1StridedFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, mixed, seqlen, batch, maxseqlen, heads, embed, scale, stream, sync, timers):
ctx.save_for_backward(mixed, seqlen)
ctx.batch = batch
ctx.maxseqlen = maxseqlen
ctx.heads = heads
ctx.embed = embed
ctx.scale = scale
ctx.sync = sync
ctx.stream = stream
ctx.timers = timers
ntokens = seqlen.sum().item()
ctx.ntokens = ntokens
ntokens2 = 0
for i in range(batch):
ntokens2 += seqlen[i]*seqlen[i]
output = torch.empty(ntokens2*heads, device="cuda", dtype=torch.float16)
if timers: timers['start_fprop'].record()
mhalib.FastBmm1Fprop(mixed, mixed, output, batch, seqlen, heads, embed, scale, True, stream, sync)
if timers: timers['stop_fprop'].record()
return output[:ntokens2*heads], mixed
@staticmethod
#def backward(ctx, grad_output):
def backward(ctx, grad_output, grad_mixed):
mixed, seqlen = ctx.saved_tensors
batch = ctx.batch
maxseqlen = ctx.maxseqlen
heads = ctx.heads
embed = ctx.embed
ntokens = ctx.ntokens
#grad_mixed = torch.empty([ntokens,heads*3*embed], device="cuda", dtype=torch.float16)
if ctx.timers: ctx.timers['start_dgrad'].record()
mhalib.FastBmm1Dgrad2(mixed, grad_output, grad_mixed, batch, seqlen, heads, embed, ctx.scale, True, ctx.stream, ctx.sync)
if ctx.timers: ctx.timers['stop_dgrad'].record()
if ctx.timers: ctx.timers['start_wgrad'].record()
mhalib.FastBmm1Dgrad1(mixed, grad_output, grad_mixed, batch, seqlen, heads, embed, ctx.scale, True, ctx.stream, ctx.sync)
if ctx.timers: ctx.timers['stop_wgrad'].record()
#return grad_mixed[:ntokens], None, None, None, None, None, None, None, None, None
return grad_mixed[:ntokens], grad_mixed, None, None, None, None, None, None, None, None, None
class Bmm1Strided(torch.nn.Module):
def __init__(self, batch, seqlen, heads, embed, scale=True, stream=True, sync=True, timer=False):
super(Bmm1Strided, self).__init__()
self.heads = heads
self.embed = embed
self.maxseqlen = seqlen
self.scale = scale
self.sync = sync
self.stream = stream
if timer:
self.timers = {'start_fprop':torch.cuda.Event(enable_timing=True),
'start_dgrad':torch.cuda.Event(enable_timing=True),
'start_wgrad':torch.cuda.Event(enable_timing=True),
'stop_fprop':torch.cuda.Event(enable_timing=True),
'stop_dgrad':torch.cuda.Event(enable_timing=True),
'stop_wgrad':torch.cuda.Event(enable_timing=True)}
else:
self.timers = None
def forward(self, mixed, batch, seqlen):
return Bmm1StridedFunction.apply(mixed, seqlen, batch, self.maxseqlen, self.heads, self.embed, self.scale, self.stream, self.sync, self.timers)
###########################################################################################
import torch
import mhalib
###########################################################################################
class Bmm2Function(torch.autograd.Function):
@staticmethod
def forward(ctx, batch1, batch2, seqlen, batch, maxseqlen, heads, embed, sync, stream):
ctx.save_for_backward(batch1, batch2, seqlen)
ctx.batch = batch
ctx.maxseqlen = maxseqlen
ctx.heads = heads
ctx.embed = embed
ctx.stream = stream
ctx.sync = sync
ntokens = seqlen.sum().item()
ctx.ntokens = ntokens
output = torch.empty([ntokens,heads,embed], device="cuda", dtype=torch.float16)
mhalib.FastBmm2Fprop(batch2.flatten().contiguous(), batch1.flatten().contiguous(), output, batch, seqlen, heads, embed, False, False, stream, sync)
return output[:ntokens]
@staticmethod
def backward(ctx, grad_output):
batch1, batch2, seqlen = ctx.saved_tensors
batch = ctx.batch
maxseqlen = ctx.maxseqlen
heads = ctx.heads
embed = ctx.embed
ntokens = ctx.ntokens
ntokens2 = 0
for i in range(batch):
ntokens2 += seqlen[i]*seqlen[i]
grad_batch1 = torch.empty([ntokens2*heads], device="cuda", dtype=torch.float16)
grad_batch2 = torch.empty([ntokens,heads*embed], device="cuda", dtype=torch.float16)
mhalib.FastBmm2Dgrad1(batch2.flatten().contiguous(), grad_output, grad_batch1, batch, seqlen, heads, embed, False, False, ctx.stream, ctx.sync)
mhalib.FastBmm2Dgrad2(grad_output, batch1, grad_batch2, batch, seqlen, heads, embed, False, False, ctx.stream, ctx.sync)
return grad_batch1[:ntokens2*heads], grad_batch2[:ntokens], None, None, None, None, None, None, None
class Bmm2(torch.nn.Module):
def __init__(self, batch, seqlen, heads, embed, stream=True, sync=True):
super(Bmm2, self).__init__()
self.heads = heads
self.embed = embed
self.maxseqlen = seqlen
self.stream = stream
self.sync = sync
def forward(self, batch1, batch2, batch, seqlen):
return Bmm2Function.apply(batch1, batch2, seqlen, batch, self.maxseqlen, self.heads, self.embed, self.stream, self.sync)
###########################################################################################
class Bmm2StridedFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, batch1, mixed, seqlen, batch, maxseqlen, heads, embed, stream, sync, timers):
ctx.save_for_backward(batch1, mixed, seqlen)
ctx.batch = batch
ctx.maxseqlen = maxseqlen
ctx.heads = heads
ctx.embed = embed
ctx.stream = stream
ctx.sync = sync
ctx.timers = timers
ntokens = seqlen.sum().item()
ctx.ntokens = ntokens
output = torch.empty([ntokens,heads,embed], device="cuda", dtype=torch.float16)
if timers: timers['start_fprop'].record()
mhalib.FastBmm2Fprop(mixed, batch1, output, batch, seqlen, heads, embed, False, True, stream, sync)
if timers: timers['stop_fprop'].record()
return output[:ntokens]
@staticmethod
def backward(ctx, grad_output):
batch1, mixed, seqlen = ctx.saved_tensors
batch = ctx.batch
maxseqlen = ctx.maxseqlen
heads = ctx.heads
embed = ctx.embed
ntokens = ctx.ntokens
ntokens2 = 0
for i in range(batch):
ntokens2 += seqlen[i]*seqlen[i]
grad_batch1 = torch.empty(ntokens2*heads, device="cuda", dtype=torch.float16)
grad_mixed = torch.empty([ntokens,heads*3*embed], device="cuda", dtype=torch.float16)
if ctx.timers: ctx.timers['start_dgrad'].record()
mhalib.FastBmm2Dgrad1(mixed, grad_output, grad_batch1, batch, seqlen, heads, embed, False, True, ctx.stream, ctx.sync)
if ctx.timers: ctx.timers['stop_dgrad'].record()
if ctx.timers: ctx.timers['start_wgrad'].record()
mhalib.FastBmm2Dgrad2(grad_output, batch1, grad_mixed, batch, seqlen, heads, embed, False, True, ctx.stream, ctx.sync)
if ctx.timers: ctx.timers['stop_wgrad'].record()
return grad_batch1[:ntokens2*heads], grad_mixed[:ntokens], None, None, None, None, None, None, None, None
class Bmm2Strided(torch.nn.Module):
def __init__(self, batch, seqlen, heads, embed, stream=True, sync=True, timer=False):
super(Bmm2Strided, self).__init__()
self.heads = heads
self.embed = embed
self.maxseqlen = seqlen
self.stream = stream
self.sync = sync
if timer:
self.timers = {'start_fprop':torch.cuda.Event(enable_timing=True),
'start_dgrad':torch.cuda.Event(enable_timing=True),
'start_wgrad':torch.cuda.Event(enable_timing=True),
'stop_fprop':torch.cuda.Event(enable_timing=True),
'stop_dgrad':torch.cuda.Event(enable_timing=True),
'stop_wgrad':torch.cuda.Event(enable_timing=True)}
else:
self.timers = None
def forward(self, batch1, mixed, batch, seqlen):
return Bmm2StridedFunction.apply(batch1, mixed, seqlen, batch, self.maxseqlen, self.heads, self.embed, self.stream, self.sync, self.timers)
###########################################################################################
# Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import glob
import h5py
import multiprocessing
import numpy as np
hdf5_compression_method = None
input_path = 'hdf5'
input_files = sorted(glob.glob(input_path + '/part*', recursive=False))
print('n_input_shards =', len(input_files))
max_pred_per_seq = 76
seq_length = 512
n_output_shards = 2048
ofile_prefix = 'chopped_2048_balanced/part_'
ofile_suffix = '_of_' + str(n_output_shards) + '.hdf5'
print('n_output_shards =', n_output_shards)
# First pass over data to get sample count (read only the smallest array to get count)
n_samples = 0
for idx, ifile in enumerate(input_files):
print("Scanning:", ifile, " -- Progress:", idx+1, '/', len(input_files))
h5_ifile = h5py.File(ifile, 'r')
f_next_sentence_labels = h5_ifile['next_sentence_labels'][:]
h5_ifile.close()
n_samples += f_next_sentence_labels.shape[0]
# Find a "nominal" number of samples per shard (calculated to always go over by one shard size)
# Find excess samples in last shard and distribute removal of excess over first "N" shards (could be done over last, but it doesn't matter and math is easier this way)
# (since 0 <= excess < nominal_shard_size, the max imbalance will be 1 sample to minimize the straggler effect)
n_sample_per_ofile_nominal = (n_samples + n_output_shards - 1) // n_output_shards
n_excess = n_output_shards * n_sample_per_ofile_nominal - n_samples # Always a positive number
ofile_handles = [h5py.File(ofile_prefix + str(x) + ofile_suffix, 'w') for x in range(n_output_shards)]
ofile_idx = 0 # which output file
ofile_entry_idx = 0 # index into an individual data element of an output file
ifile_entry_idx = 0
n_samples_in_this_shard = n_sample_per_ofile_nominal - 1
o_input_ids = np.ndarray((n_samples_in_this_shard, seq_length))
o_input_masks = np.ndarray((n_samples_in_this_shard, seq_length))
o_segment_ids = np.ndarray((n_samples_in_this_shard, seq_length))
o_masked_lm_positions = np.ndarray((n_samples_in_this_shard, max_pred_per_seq))
o_masked_lm_ids = np.ndarray((n_samples_in_this_shard, max_pred_per_seq))
o_next_sentence_labels = np.ndarray((n_samples_in_this_shard))
for ifile in input_files:
print("Processing:", ifile, " -- Progress:", idx+1, '/', len(input_files))
h5_ifile = h5py.File(ifile, 'r')
ifile_entry_idx = 0
f_input_ids = h5_ifile['input_ids'][:]
f_input_masks = h5_ifile['input_mask'][:]
f_segment_ids = h5_ifile['segment_ids'][:]
f_masked_lm_positions = h5_ifile['masked_lm_positions'][:]
f_masked_lm_ids = h5_ifile['masked_lm_ids'][:]
f_next_sentence_labels = h5_ifile['next_sentence_labels'][:]
h5_ifile.close()
# This could be vectorized but keeping it simple due to lack of time
while ifile_entry_idx < f_input_ids.shape[0]:
if ofile_entry_idx == n_samples_in_this_shard:
ofile_handles[ofile_idx].create_dataset("input_ids", data=o_input_ids, dtype='i4', compression=hdf5_compression_method)
ofile_handles[ofile_idx].create_dataset("input_mask", data=o_input_masks, dtype='i1', compression=hdf5_compression_method)
ofile_handles[ofile_idx].create_dataset("segment_ids", data=o_segment_ids, dtype='i1', compression=hdf5_compression_method)
ofile_handles[ofile_idx].create_dataset("masked_lm_positions", data=o_masked_lm_positions, dtype='i4', compression=hdf5_compression_method)
ofile_handles[ofile_idx].create_dataset("masked_lm_ids", data=o_masked_lm_ids, dtype='i4', compression=hdf5_compression_method)
ofile_handles[ofile_idx].create_dataset("next_sentence_labels", data=o_next_sentence_labels, dtype='i1', compression=hdf5_compression_method)
ofile_handles[ofile_idx].flush()
ofile_handles[ofile_idx].close()
ofile_entry_idx = 0
ofile_idx += 1
print("Opening output idx:", ofile_idx)
n_samples_in_this_shard = n_sample_per_ofile_nominal
if ofile_entry_idx < n_excess:
n_samples_in_this_shard -= 1
o_input_ids = np.ndarray((n_samples_in_this_shard, seq_length))
o_input_masks = np.ndarray((n_samples_in_this_shard, seq_length))
o_segment_ids = np.ndarray((n_samples_in_this_shard, seq_length))
o_masked_lm_positions = np.ndarray((n_samples_in_this_shard, max_pred_per_seq))
o_masked_lm_ids = np.ndarray((n_samples_in_this_shard, max_pred_per_seq))
o_next_sentence_labels = np.ndarray((n_samples_in_this_shard))
o_input_ids[ofile_entry_idx] = f_input_ids[ifile_entry_idx]
o_input_masks[ofile_entry_idx] = f_input_masks[ifile_entry_idx]
o_segment_ids[ofile_entry_idx] = f_segment_ids[ifile_entry_idx]
o_masked_lm_positions[ofile_entry_idx] = f_masked_lm_positions[ifile_entry_idx]
o_masked_lm_ids[ofile_entry_idx] = f_masked_lm_ids[ifile_entry_idx]
o_next_sentence_labels[ofile_entry_idx] = f_next_sentence_labels[ifile_entry_idx]
ofile_entry_idx += 1
ifile_entry_idx += 1
#!/bin/bash
# Copyright 2018 MLBenchmark Group. 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.
# ==============================================================================
filein=$1
fileout=$2
echo "Further clean up: $filein => $fileout"
cmd="cat $filein "
cmd+="| grep -v '^<doc [^>]*>$' "
cmd+="| grep -vE '\[\[Category:[^][]*\]\]' "
cmd+="| sed 's/\[\[\([^]|[]*\)\]\]/\1/g' "
cmd+="| sed 's/\[\[\([^]|[]*\)\]\]/\1/g' "
cmd+="| sed 's/\[\[[^]|[]*|\([^]|[]*\)\]\]/\1/g' "
cmd+="| sed 's/\[\[[^]|[]*|\([^]|[]*\)\]\]/\1/g' "
cmd+="| sed 's/\[\[[:]*[Ff]ile:[^][]*\]\]//g' "
cmd+="| sed 's/\[\[[Mm]edia:[^][]*\]\]//g' "
cmd+="| sed 's/\[\[[Ii]mage:[^][]*\]\]//g' "
cmd+="| sed 's/\[\([^]|[]*\)\]/\1/g' "
cmd+="| sed 's/\[\[\([^][]*\)\]\]//g' "
cmd+="| sed 's/alt=//g' "
cmd+="| sed 's/<\/doc>/\r/g' "
cmd+="| sed 's/<chem\([^<]*\)<\/chem>/\1/g' "
cmd+="| sed 's/<ins\([^<]*\)<\/ins>/\1/g' "
cmd+="| sed 's/<\, ref \([^<]*\)<\/ref>//g' "
cmd+="| sed 's/<includeonly\([^<]*\)<\/includeonly>//g' "
cmd+="| sed 's/<graph\([^<]*\)<\/graph>//g' "
cmd+="| sed 's/<section\([^\\]*\)\/>//g' "
cmd+="| sed 's/<meta\([^\\]*\)\/>//g' "
cmd+="| sed 's/<hr\([^\\]*\)\/>//g' "
cmd+="| sed 's/<gallery\([^>]*\)>//g' "
cmd+="| sed 's/<ref\([^<]*\)<\/ref>//g' "
cmd+="| sed 's/<ref\([^>]*\)>//g' "
cmd+="| sed 's/<http\([^>]*\)>//g' "
cmd+="| sed 's/<Ref\([^>]*\)>//g' "
cmd+="| sed 's/<mapframe \([^\/]*\)\/>//g' "
cmd+="| sed 's/<mapframe\([^>]*\)>//g' "
cmd+="| sed 's/<\/mapframe>//g' "
cmd+="| sed 's/<poem>//g' "
cmd+="| sed 's/<\/poem>//g' "
cmd+="| sed 's/<math>//g' "
cmd+="| sed 's/<\/math>//g' "
cmd+="| sed 's/<ref>//g' "
cmd+="| sed 's/<\/ref>//g' "
cmd+="| sed 's/<div\([^>]*\)>//g' "
cmd+="| sed 's/<\/div\([^>]*\)>//g' "
cmd+="| sed 's/<\/div style>//g' "
cmd+="| sed 's/<\/div>//g' "
cmd+="| sed 's/<sup>//g' "
cmd+="| sed 's/<\/sup>//g' "
cmd+="| sed 's/<br>//g' "
cmd+="| sed 's/<\/br>//g' "
cmd+="| sed 's/<BR>//g' "
cmd+="| sed 's/<\/BR>//g' "
cmd+="| sed 's/<Br>//g' "
cmd+="| sed 's/<\/Br>//g' "
cmd+="| sed 's/<del>//g' "
cmd+="| sed 's/<\/del>//g' "
cmd+="| sed 's/<nowiki>//g' "
cmd+="| sed 's/<\/nowiki>//g' "
cmd+="| sed 's/<NOWIKI>//g' "
cmd+="| sed 's/<\/NOWIKI>//g' "
cmd+="| sed 's/<onlyinclude>//g' "
cmd+="| sed 's/<\/onlyinclude>//g' "
cmd+="| sed 's/<includeonly>//g' "
cmd+="| sed 's/<\/includeonly>//g' "
cmd+="| sed 's/<small>//g' "
cmd+="| sed 's/<\/small>//g' "
cmd+="| sed 's/<chem>//g' "
cmd+="| sed 's/<\/chem>//g' "
cmd+="| sed 's/<noinclude>//g' "
cmd+="| sed 's/<\/noinclude>//g' "
cmd+="| sed 's/<gallery>//g' "
cmd+="| sed 's/<\/gallery>//g' "
cmd+="| sed 's/<graph>{//g' "
cmd+="| sed 's/<graph>//g' "
cmd+="| sed 's/}<\/graph>//g' "
cmd+="| sed 's/<\/graph>//g' "
cmd+="| sed 's/<\/references>//g' "
cmd+="| sed 's/<poem \([^>]*\)>//g' "
# cmd+="| grep -v '^[ \t]*$' "
cmd+="> $fileout"
bash -c "${cmd[@]}"
# Copyright 2018 MLBenchmark Group. 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.
# ==============================================================================
# Lint as: python3
"""Script to clean up input wiki dump for BERT input."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import glob
import io
import logging
import multiprocessing
import os
import time
parser = argparse.ArgumentParser(description='Wiki clean up for BERT.')
parser.add_argument(
'--data',
type=str,
default='./wiki_??',
help='Input files. Default is "./wiki_??"')
parser.add_argument(
'--input_suffix',
type=str,
default='',
help='Suffix for input files. Default is ""')
parser.add_argument(
'--output_suffix',
type=str,
default='.1',
help='Suffix for output files. Default is ".1"')
parser.add_argument(
'--nworker',
type=int,
default=72,
help='Number of workers for parallel processing.')
args = parser.parse_args()
def process_one_file(one_input):
"""Remove <doc> tag and title of pages, for one file."""
input_filename = one_input + args.input_suffix
output_filename = one_input + args.output_suffix
logging.info('Processing %s => %s', input_filename, output_filename)
with io.open(input_filename, 'r', encoding='utf-8') as fin:
with io.open(output_filename, 'w', encoding='utf-8') as fout:
keep_next_line = True
for line in fin:
if not keep_next_line:
keep_next_line = True
continue
if '<doc' in line:
keep_next_line = False
fout.write(u'\n')
continue
if '</doc>' in line:
continue
if len(line) == 1:
continue
fout.write(line)
if __name__ == '__main__':
input_files = sorted(glob.glob(os.path.expanduser(args.data)))
num_files = len(input_files)
num_workers = args.nworker
logging.basicConfig(level=logging.INFO)
logging.info('Number of input files to process = %d', num_files)
tic = time.time()
p = multiprocessing.Pool(num_workers)
p.map(process_one_file, input_files)
toc = time.time()
logging.info('Processed %s in %.2f sec', args.data, toc - tic)
#!/bin/bash
# Copyright (c) 2019 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.
input_path=${1}
output_dir="hdf5"
input_file=$(basename $input_path)
mkdir -p ${output_dir}
python3 ../create_pretraining_data.py \
--input_file=${input_path} \
--output_file="${output_dir}/${input_file}" \
--vocab_file=vocab.txt \
--do_lower_case=True \
--max_seq_length=512 \
--max_predictions_per_seq=76 \
--masked_lm_prob=0.15 \
--random_seed=12345 \
--dupe_factor=10
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment