diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/HLS-Gaudi2-TF/defaults.cfg b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/HLS-Gaudi2-TF/defaults.cfg new file mode 100644 index 0000000000000000000000000000000000000000..6c6f552fdffcbd89f7b5443d075d83519196aecc --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/HLS-Gaudi2-TF/defaults.cfg @@ -0,0 +1,40 @@ +#!/bin/bash +DATESTAMP=`date +'%y%m%d%H%M%S'` +export INPUT_FILES_DIR_UNPACKED=/root/datasets/tensorflow_bert/unpacked_data +export INPUT_FILES_DIR_PACKED=/root/datasets/tensorflow_bert/packed_data_500 +export EVAL_FILES_DIR=/root/datasets/tensorflow_bert/eval_dataset +export INITIAL_CHECKPOINT=/root/datasets/tensorflow_bert/checkpoint/model.ckpt-28252 +export BERT_CONFIG_DIR=/root/datasets/tensorflow_bert/checkpoint +export OUTPUT_DIR=/tmp/bert_pretrain/phase_2 +export LOG_DIR=/tmp/bert_pretrain/phase_2 +export TRAIN_BATCH_SIZE=28 +export EVAL_BATCH_SIZE=125 +export MAX_EVAL_STEPS=10 +export NUM_DIST_EVAL_WORKERS=8 +export TRAIN_STEPS=6700 +export WARMUP_STEPS=0 +export LEARNING_RATE=0.000425 +export LAMB_BETA_1=0.9 +export LAMB_BETA_2=0.999 +export EPSILON=1e-06 +export LAMB_WEIGHT_DECAY_RATE=0.01 +export LAMB_LEARNING_RATE_DECAY_POLY_POWER=1.0 +export NUM_ACCUMULATION_STEPS=2 +export SAMPLES_START_EVAL=0 +export SAVE_CHECKPOINTS_STEPS=335 +export PACKED_DATA=True +export USE_HOROVOD=True +export HLS_TYPE="HLS2" +export NUM_WORKERS_TOTAL=8 +export TF_CPU_RUNTIME_FALLBACK=forbid +export TF_HCCL_MEMORY_ALLOWANCE_MB=1536 +export HABANA_INITIAL_WORKSPACE_SIZE_MB=4600 +export CPU_BIND_TYPE=cpu +export USE_LIGHTWEIGHT_CHECKPOINT=True +export DO_TRAIN=True +export DO_EVAL=True +export USE_ASYNC_CHECKPOINTING=True +export EXPERIMENTAL_SLACK=True +export SIGNALING_FROM_GRAPH=0 + +unset MPI_TCP_INCLUDE diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/HLS-Gaudi2-TF/launch_bert_hvd.sh b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/HLS-Gaudi2-TF/launch_bert_hvd.sh new file mode 100644 index 0000000000000000000000000000000000000000..26039a5b65fbb511954f4c7481ecc56832142e38 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/HLS-Gaudi2-TF/launch_bert_hvd.sh @@ -0,0 +1,611 @@ +#!/bin/bash + +DEBUG=${DEBUG:-0} +if [[ $DEBUG -eq 1 ]]; then + set -x + env +fi + +# Basic paths +SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) +export BASE_PATH="$( cd "$(dirname "$(readlink -f ${SCRIPT_DIR}/defaults.cfg)" )" && pwd)" +exit_code=0 + +OMPI_PREFIX=$(which mpirun) +export OMPI_PREFIX=$(dirname $(dirname ${OMPI_PREFIX}) ) + +function help() +{ + echo "Usage:" + echo "$0 [ -key1 value1 -key2 value2 .... -keyn valuen ]" + echo "-c | --config Configuration file path (defaults to ./defaults.cfg)" + echo "-hf | --hostfile Host file path, 'localhost' is used if no file is provided" + echo "-u | --use_horovod Enable (0) or disable (1) horovod use" + echo "-ws | --warmup_steps" + echo "-lr | --learning_rate" + echo "-st | --stop_threshold" + echo "-acs | --num_accumul_steps" + echo "-tbs | --train_batchsize" + echo "-ebs | --eval_batchsize" + echo "-ts | --train_steps" + echo "-lb1 | --lamb_beta_1" + echo "-lb2 | --lamb_beta_2" + echo "-ep | --epsilon" + echo "-lwd | --lamb_weight_decay_rate" + echo "-ldp | --lamb_lr_decay_poly_power" + echo "-sbe | --samples_btw_eval" + echo "-sse | --samples_start_eval" + echo "-mes | --max_eval_steps" + echo "-w | --num_workers_total" + echo "-p | --packed_data Packed (0) or unpacked (1)" + echo "-sch | --save_checkpoints_steps" + echo "-cpu | --cpu_bind_type [ none | cpu | numa ]" + echo "-inputf | --input_files_dir" + echo "-evalf | --eval_files_dir" + echo "-od | --output_dir" + echo "-ckpt | --initial_checkpoint" + echo "-config | --config_dir" + echo "-hls | --hls_type" + echo "-tcp | --mpi_tcp_include" + echo "-dram | --use_dram_output" + echo "-lw | --light_weight" + echo "-lwi | --light_weight_impl [ basic (default) | sharded ]" + echo "-ac | --async_checkpointing" + echo "-ld | --log_dir" + echo "--do_train" + echo "--do_eval" + echo "--experimental_slack" + echo "-ndew | --num_dist_eval_workers Number of workers participating in distributed evaluation" + echo "-opt | --optimizer Type of optimizer, available options: 'lamb', 'sharded_lamb', 'adam'" + echo "-sfg | --signaling_from_graph Enable (1) or disable (0) SFG optimization." +} +#echo "-sws | --start_warmup_steps" + +# Parse command line options +unset __config +unset __hostfile +unset __use_horovod +unset __warmup_steps +unset __learning_rate +unset __stop_threshold +unset __num_accumul_steps +unset __train_batchsize +unset __eval_batchsize +unset __train_steps +#unset __start_warmup_steps +unset __lamb_beta_1 +unset __lamb_beta_2 +unset __epsilon +unset __lamb_weight_decay_rate +unset __lamb_lr_decay_poly_power +unset __samples_btw_eval +unset __samples_start_eval +unset __max_eval_steps +unset __num_workers_total +unset __packed_data +unset __save_checkpoints_steps +unset __cpu_bind_type +unset __input_files_dir +unset __eval_files_dir +unset __output_dir +unset __initial_checkpoint +unset __config_dir +unset __hls_type +unset __mpi_tcp_include +unset __use_dram_output +unset __light_weight +unset __light_weight_impl +unset __async_checkpointing +unset __log_dir +unset __do_train +unset __do_eval +unset __experimental_slack +unset __num_dist_eval_workers +unset __optimizer +unset __aux_scirpt_params +unset __ssh_port +unset __signaling_from_graph + +while [ -n "$1" ]; do + case $1 in + -c | --config ) + shift + __config=$1 + ;; + -hf | --hostfile) + shift + __hostfile=$1 + ;; + -u | --use_horovod ) + shift + __use_horovod=$1 + ;; + -ws | --warmup_steps ) + shift + __warmup_steps=$1 + ;; + -lr | --learning_rate ) + shift + __learning_rate=$1 + ;; + -st | --stop_threshold ) + shift + __stop_threshold=$1 + ;; + -acs | --num_accumul_steps ) + shift + __num_accumul_steps=$1 + ;; + -tbs | --train_batchsize ) + shift + __train_batchsize=$1 + ;; + -ebs | --eval_batchsize) + shift + __eval_batchsize=$1 + ;; + -ts | --train_steps) + shift + __train_steps=$1 + ;; + -lb1 | --lamb_beta_1) + shift + __lamb_beta_1=$1 + ;; + -lb2 | --lamb_beta_2) + shift + __lamb_beta_2=$1 + ;; + -ep | --epsilon) + shift + __epsilon=$1 + ;; + -lwd | --lamb_weight_decay_rate) + shift + __lamb_weight_decay_rate=$1 + ;; + -ldp | --lamb_lr_decay_poly_power) + shift + __lamb_lr_decay_poly_power=$1 + ;; + -sbe | --samples_btw_eval) + shift + __samples_btw_eval=$1 + ;; + -sse | --samples_start_eval) + shift + __samples_start_eval=$1 + ;; + -mes | --max_eval_steps) + shift + __max_eval_steps=$1 + ;; + -w | --num_workers_total) + shift + __num_workers_total=$1 + ;; + -p | --packed_data) + shift + __packed_data=$1 + ;; + -sch | --save_checkpoints_steps) + shift + __save_checkpoints_steps=$1 + ;; + -cpu | --cpu_bind_type) + shift + __cpu_bind_type=$1 + case ${__cpu_bind_type} in + numa | cpu | none ) + ;; + *) + echo "--cpu-pin must be one of the following numa | cpu | none " + exit 1 + esac + ;; + -inputf | --input_files_dir) + shift + __input_files_dir=$1 + ;; + -sfg | --signaling_from_graph) + shift + __signaling_from_graph=$1 + ;; + -evalf | --eval_files_dir) + shift + __eval_files_dir=$1 + ;; + -od | --output_dir) + shift + __output_dir=$1 + ;; + -ckpt | --initial_checkpoint) + shift + __initial_checkpoint=$1 + ;; + -config | --config_dir) + shift + __config_dir=$1 + ;; + -hls | --hls_type) + shift + __hls_type=$1 + ;; + -tcp | --mpi_tcp_include) + shift + __mpi_tcp_include=$1 + ;; + -dram | --use_dram_output) + shift + __use_dram_output=$1 + ;; + -lw | --light_weight) + shift + __light_weight=$1 + ;; + -lwi | --light_weight_impl) + shift + __light_weight_impl=$1 + ;; + -ac | --async_checkpointing) + shift + __async_checkpointing=$1 + ;; + -ld | --log_dir) + shift + __log_dir=$1 + ;; + --do_train) + shift + __do_train=$1 + ;; + --do_eval) + shift + __do_eval=$1 + ;; + --experimental_slack) + shift + __experimental_slack=$1 + ;; + -ndew | --num_dist_eval_workers) + shift + __num_dist_eval_workers=$1 + ;; + -opt | --optimizer) + shift + __optimizer=$1 + ;; + -port | --ssh_port) + shift + __ssh_port=$1 + ;; + -h | --help) + help + exit 1 + ;; + * ) + __aux_param=$1 + shift + echo "The parameter $1 will be passed directly to python script" + __aux_scirpt_params="${__aux_scirpt_params}:${__aux_param}=${1}" + ;; + esac + shift +done + +export CFG_FILE=${__config:-"${BASE_PATH}/defaults.cfg"} +if [[ -f ${CFG_FILE} ]]; then + source ${CFG_FILE} +else + echo "Could not find ${CFG_FILE}" + exit 1 +fi + +# Set default values for environmental variable +export HOST_FILE=${__hostfile:-"${OMPI_MCA_orte_default_hostfile}"} +export SSH_PORT=${__ssh_port:-"3022"} + +if [[ -z "${HABANA_LOGS}" ]]; then + export HABANA_LOGS="/var/logs/habana_logs" + echo "Creating default directory for habana_logs." + mkdir -p $HABANA_LOGS +fi +export EVAL_FILES_DIR=${EVAL_FILES_DIR} +export OUTPUT_DIR=${OUTPUT_DIR} +export PHASE1_CKPT=${INITIAL_CHECKPOINT} +export INITIAL_CHECKPOINT=${INITIAL_CHECKPOINT} +export BERT_CONFIG_DIR=${BERT_CONFIG_DIR} +export NUM_WORKERS_PER_HLS=${NUM_WORKERS_PER_HLS} +export OPTIMIZE_DMA_ENGINES_ALLOCATION=${OPTIMIZE_DMA_ENGINES_ALLOCATION} +export TF_CPU_RUNTIME_FALLBACK=${TF_CPU_RUNTIME_FALLBACK} +export TF_HCCL_MEMORY_ALLOWANCE_MB=${TF_HCCL_MEMORY_ALLOWANCE_MB} +export HABANA_INITIAL_WORKSPACE_SIZE_MB=${HABANA_INITIAL_WORKSPACE_SIZE_MB} + +# Override defaults with command line options if needed +export MPI_TCP_INCLUDE=${__mpi_tcp_include:-$MPI_TCP_INCLUDE} +export USE_HOROVOD=${__use_horovod:-$USE_HOROVOD} +export WARMUP_STEPS=${__warmup_steps:-$WARMUP_STEPS} +export LEARNING_RATE=${__learning_rate:-$LEARNING_RATE} +export STOP_THRESHOLD=${__stop_threshold:-$STOP_THRESHOLD} +export NUM_ACCUMULATION_STEPS=${__num_accumul_steps:-$NUM_ACCUMULATION_STEPS} +export TRAIN_BATCH_SIZE=${__train_batchsize:-$TRAIN_BATCH_SIZE} +export EVAL_BATCH_SIZE=${__eval_batchsize:-$EVAL_BATCH_SIZE} +export TRAIN_STEPS=${__train_steps:-$TRAIN_STEPS} +export LAMB_BETA_1=${__lamb_beta_1:-$LAMB_BETA_1} +export LAMB_BETA_2=${__lamb_beta_2:-$LAMB_BETA_2} +export EPSILON=${__epsilon:-$EPSILON} +export LAMB_WEIGHT_DECAY_RATE=${__lamb_weight_decay_rate:-$LAMB_WEIGHT_DECAY_RATE} +export LAMB_LEARNING_RATE_DECAY_POLY_POWER=${__lamb_lr_decay_poly_power:-$LAMB_LEARNING_RATE_DECAY_POLY_POWER} +export SAMPLES_START_EVAL=${__samples_start_eval:-$SAMPLES_START_EVAL} +export MAX_EVAL_STEPS=${__max_eval_steps:-$MAX_EVAL_STEPS} +export NUM_WORKERS_TOTAL=${__num_workers_total:-$NUM_WORKERS_TOTAL} +export PACKED_DATA=${__packed_data:-$PACKED_DATA} +export SAVE_CHECKPOINTS_STEPS=${__save_checkpoints_steps:-$SAVE_CHECKPOINTS_STEPS} +SAMPLES_BETWEEN_EVAL=$(($TRAIN_BATCH_SIZE*$NUM_WORKERS_TOTAL*$NUM_ACCUMULATION_STEPS*$SAVE_CHECKPOINTS_STEPS)) +export SAMPLES_BETWEEN_EVAL=${__samples_btw_eval:-$SAMPLES_BETWEEN_EVAL} +export CPU_BIND_TYPE=${__cpu_bind_type:-$CPU_BIND_TYPE} +export EVAL_FILES_DIR=${__eval_files_dir:-$EVAL_FILES_DIR} +export SIGNALING_FROM_GRAPH=${__signaling_from_graph:-$SIGNALING_FROM_GRAPH} +export OUTPUT_DIR=${__output_dir:-$OUTPUT_DIR} +export PHASE1_CKPT=${__initial_checkpoint:-$INITIAL_CHECKPOINT} +export BERT_CONFIG_DIR=${__config_dir:-$BERT_CONFIG_DIR} +export HLS_TYPE=${__hls_type:-$HLS_TYPE} +export USE_DRAM_OUTPUT=${__use_dram_output:-"True"} +export USE_LIGHTWEIGHT_CHECKPOINT=${__light_weight:-$USE_LIGHTWEIGHT_CHECKPOINT} +export LIGHTWEIGHT_CHECKPOINT_IMPL=${__light_weight_impl:-"basic"} +export USE_ASYNC_CHECKPOINTING=${__async_checkpointing:-$USE_ASYNC_CHECKPOINTING} +export LOG_DIR=${__log_dir:-$LOG_DIR} +export DO_TRAIN=${__do_train:-$DO_TRAIN} +export DO_EVAL=${__do_eval:-$DO_EVAL} +export EXPERIMENTAL_SLACK=${__experimental_slack:-$EXPERIMENTAL_SLACK} +export NUM_DIST_EVAL_WORKERS=${__num_dist_eval_workers:-$NUM_DIST_EVAL_WORKERS} +export AUX_PARAMS=${__aux_scirpt_params:-$AUX_PARAMS} +export OPTIMIZER=${__optimizer:-$OPTIMIZER} + +if [[ "$HLS_TYPE" == "HLS2" ]]; then + export NUM_WORKERS_PER_HLS=8 +else + "============== WRONG HLS TYPE!! ===============" + exit -1 +fi + +if [ "$PACKED_DATA" == "False" ]; then + export INPUT_FILES_DIR=${__input_files_dir:-$INPUT_FILES_DIR_UNPACKED} +else + export INPUT_FILES_DIR=${__input_files_dir:-$INPUT_FILES_DIR_PACKED} +fi + +if [ "$USE_HOROVOD" == "True" ]; then + export HOROVOD_STALL_CHECK_DISABLE=1 + echo HOROVOD_STALL_CHECK_DISABLE=$HOROVOD_STALL_CHECK_DISABLE + + # SAO:ON by default + export TF_DISABLE_SCOPED_ALLOCATOR=${TF_DISABLE_SCOPED_ALLOCATOR:-False} + echo TF_DISABLE_SCOPED_ALLOCATOR=$TF_DISABLE_SCOPED_ALLOCATOR +fi + +function getmulti_hls_ips() +{ + multi_hcl_ip="MULTI_HLS_IPS=" + hostsFile=$1 + firstHost=1 + hostCount=0 + + # iterate over non-empty and non-commented lines + for h in $(cat $hostsFile | sed '/^$/d' | grep -v '^#'); do + if [[ $firstHost -eq 1 ]]; then + firstHost=0 + else + multi_hcl_ip+="," + fi + multi_hcl_ip+=$h + hostCount=$((hostCount + 1)) + done + + echo "[getmulti_hls_ips] Host Count : $hostCount" + echo "[getmulti_hls_ips] Exporting : $multi_hcl_ip" + export $multi_hcl_ip +} + + +function run_per_ip() +{ + if [ -n "$OMPI_COMM_WORLD_SIZE" ]; then + print_error "Function run_per_ip is not meant to be ran from within an OpenMPI context. It is intended to invoke mpirun by itelf." + exit 1 + fi + _cmd="$@" + # Due to technical difficulties with the following solution, the _cmd stderr shall be redirected to stdout. + if [[ -z ${MULTI_HLS_IPS} ]]; then + echo "[launch_bert_hvd] MULTI_HLS_IPS undefined - maybe a missing /root/shared/hosts file?" + exit -1 + else + if [ -n "$MPI_TCP_INCLUDE" ]; then + _option_btl_tcp_if_include="--mca btl_tcp_if_include ${MPI_TCP_INCLUDE}" + else + _option_btl_tcp_if_include="" + fi + mpirun --allow-run-as-root \ + --mca plm_rsh_args -p${SSH_PORT} \ + ${_option_btl_tcp_if_include} \ + --tag-output \ + --merge-stderr-to-stdout \ + --prefix ${OMPI_PREFIX} \ + -H ${MULTI_HLS_IPS} \ + bash -c "`declare`; `declare -x`; ($_cmd 2>&1)" 2>/dev/null + fi +} + +export MULTI_HLS_IPS=localhost +if [[ -f ${HOST_FILE} ]]; then + getmulti_hls_ips ${HOST_FILE} +fi + +# Create recipes directory if it does not exist and adjust dirctory name +# if we are collecting traces - which require debug information +run_per_ip mkdir -p ${OUTPUT_DIR} # 2>/dev/null +run_per_ip rm -rf ${OUTPUT_DIR}/* # 2>/dev/null +run_per_ip mkdir -p ${LOG_DIR} +mkdir -p ${LOG_DIR} + +run_per_ip pip install -r $BASE_PATH/../TensorFlow/nlp/bert/requirements.txt + +#run_per_ip rm -rf /tmp/checkpoint /tmp/eval /tmp/events.out.tfevents.* /tmp/graph.pbtxt /tmp/model.ckpt-* +#run_per_ip rm -rf /tmp/rank_*/checkpoint /tmp/rank_*/eval /tmp/rank_*/events.out.tfevents.* /tmp/rank_*/graph.pbtxt /tmp/rank_*/model.ckpt-* + +function setup_libjemalloc() +{ + local libjemalloc_1_lib="libjemalloc.so.1" + local libjemalloc_2_lib="libjemalloc.so.2" + local is_v2_not_present=`LD_PRELOAD=${libjemalloc_2_lib} head -0 2>&1 > /dev/null` + + if [ -z "${is_v2_not_present}" ]; then + export LD_PRELOAD=${libjemalloc_2_lib}:$LD_PRELOAD + else + export LD_PRELOAD=${libjemalloc_1_lib}:$LD_PRELOAD + fi +} +run_per_ip setup_libjemalloc + +if [[ -z ${MULTI_HLS_IPS} ]]; then + echo "[launch_bert_hvd] MULTI_HLS_IPS undefined - maybe a missing /root/shared/hosts file?" + exit -1 +else + IFS=',' read -ra IPS <<< "$MULTI_HLS_IPS" + let MPI_NP=${#IPS[@]}*${NUM_WORKERS_PER_HLS} + export NUM_WORKERS_TOTAL=${NUM_WORKERS_TOTAL:-$MPI_NP} + + if [[ $NUM_WORKERS_TOTAL != $MPI_NP ]]; then + echo $NUM_WORKERS_TOTAL $MPI_NP + echo "=============== WRONG NUMBER_WORKERS_TOTAL!! ===============" + exit -1 + fi + + echo NUM_WORKERS_TOTAL=$NUM_WORKERS_TOTAL + + function generate_mpi_hostfile() + { + echo "Generating MPI hostfile..." + local num_nodes=${2:-8} + local file_name="hostfile" + export MPI_HOSTFILE_PATH=$1/${file_name} + + rm -rf ${MPI_HOSTFILE_PATH} + echo "PATH: ${MPI_HOSTFILE_PATH}" + touch ${MPI_HOSTFILE_PATH} + + IFS=',' read -ra IPS <<< "$MULTI_HLS_IPS" + for i in "${IPS[@]}"; do + echo "$i slots=${num_nodes}" >> ${MPI_HOSTFILE_PATH} + done + echo "Config: " + cat ${MPI_HOSTFILE_PATH} + } + + generate_mpi_hostfile ${OUTPUT_DIR} ${NUM_WORKERS_PER_HLS} + + export testdate=`date +%Y-%m-%d` + export testtime=`date +%H%M%S` + export OUTPUT_DIR=${__output_dir:-/root/scratch/bert/bert_gaudi${NUM_WORKERS_TOTAL}_${testdate}_${testtime}} + + run_per_ip mkdir -p ${OUTPUT_DIR} + + run_per_ip rm -f $LOG_DIR/result_* + run_per_ip rm -f ${LOG_DIR}/tf_bert_pretraining_lamb.log + + LOGFILE=$LOG_DIR/tf_bert_pretraining_lamb.log + export TF_RECIPE_CACHE_PATH=/tmp/bert_pretrain/phase_2 + run_per_ip mkdir -p $TF_RECIPE_CACHE_PATH + + MPI_MAP_BY=socket + MPI_MAP_BY_PE=`lscpu | grep "^CPU(s):"| awk -v NUM=${NUM_WORKERS_PER_HLS} '{print int($2/NUM/2)}'` + if [[ "$CPU_BIND_TYPE" == "numa" || "$CPU_BIND_TYPE" == "none" ]]; then + MPIRUN_ARGS_MAP_BY_PE="-bind-to none" + else + MPIRUN_ARGS_MAP_BY_PE="--bind-to core --map-by $MPI_MAP_BY:PE=$MPI_MAP_BY_PE" + fi + + if [ -n "$MPI_TCP_INCLUDE" ]; then + _option_btl_tcp_if_include="--mca btl_tcp_if_include ${MPI_TCP_INCLUDE}" + else + _option_btl_tcp_if_include="" + fi + + TRAINING_COMMAND="mpirun --allow-run-as-root \ + --display-map \ + --report-bindings \ + --bind-to none \ + -np ${NUM_WORKERS_TOTAL}\ + --hostfile ${MPI_HOSTFILE_PATH} \ + --prefix ${OMPI_PREFIX} \ + --mca plm_rsh_args -p${SSH_PORT} \ + ${_option_btl_tcp_if_include} \ + --merge-stderr-to-stdout \ + --tag-output \ + --output-filename ${LOG_DIR}/bert_log \ + -x USE_HOROVOD=${USE_HOROVOD} \ + -x TF_MODULES_RELEASE_BUILD=/usr/lib/habanalabs/ \ + -x HABANA_LOGS=${HABANA_LOGS} \ + -x LEARNING_RATE=${LEARNING_RATE} \ + -x STOP_THRESHOLD=${STOP_THRESHOLD} \ + -x NUM_ACCUMULATION_STEPS=${NUM_ACCUMULATION_STEPS} \ + -x TRAIN_BATCH_SIZE=${TRAIN_BATCH_SIZE} \ + -x EVAL_BATCH_SIZE=${EVAL_BATCH_SIZE} \ + -x TRAIN_STEPS=${TRAIN_STEPS} \ + -x NUM_WORKERS_TOTAL=${NUM_WORKERS_TOTAL} \ + -x WARMUP_STEPS=${WARMUP_STEPS} \ + -x LAMB_BETA_1=${LAMB_BETA_1} \ + -x LAMB_BETA_2=${LAMB_BETA_2} \ + -x EPSILON=${EPSILON} \ + -x LAMB_WEIGHT_DECAY_RATE=${LAMB_WEIGHT_DECAY_RATE} \ + -x LAMB_LEARNING_RATE_DECAY_POLY_POWER=${LAMB_LEARNING_RATE_DECAY_POLY_POWER} \ + -x SAMPLES_BETWEEN_EVAL=${SAMPLES_BETWEEN_EVAL} \ + -x SAMPLES_START_EVAL=${SAMPLES_START_EVAL} \ + -x MAX_EVAL_STEPS=${MAX_EVAL_STEPS} \ + -x INPUT_FILES_DIR=${INPUT_FILES_DIR} \ + -x EVAL_FILES_DIR=${EVAL_FILES_DIR} \ + -x OUTPUT_DIR=${OUTPUT_DIR} \ + -x PHASE1_CKPT=${PHASE1_CKPT} \ + -x BERT_CONFIG_DIR=${BERT_CONFIG_DIR} \ + -x OPTIMIZE_DMA_ENGINES_ALLOCATION=${OPTIMIZE_DMA_ENGINES_ALLOCATION} \ + -x TF_CPU_RUNTIME_FALLBACK=${TF_CPU_RUNTIME_FALLBACK} \ + -x TF_HCCL_MEMORY_ALLOWANCE_MB=${TF_HCCL_MEMORY_ALLOWANCE_MB} \ + -x HABANA_INITIAL_WORKSPACE_SIZE_MB=${HABANA_INITIAL_WORKSPACE_SIZE_MB} \ + -x HLS_TYPE=${HLS_TYPE} \ + -x MPI_TCP_INCLUDE=${MPI_TCP_INCLUDE} \ + -x SAVE_CHECKPOINTS_STEPS=${SAVE_CHECKPOINTS_STEPS} \ + -x PACKED_DATA=${PACKED_DATA} \ + -x TESTDATE=${testdate} \ + -x TESTTIME=${testtime} \ + -x CPU_BIND_TYPE=${CPU_BIND_TYPE} \ + ${MPIRUN_ARGS_MAP_BY_PE} \ + -x NUM_WORKERS_PER_HLS=${NUM_WORKERS_PER_HLS} \ + -x USE_DRAM_OUTPUT=${USE_DRAM_OUTPUT} \ + -x USE_LIGHTWEIGHT_CHECKPOINT=${USE_LIGHTWEIGHT_CHECKPOINT} \ + -x LIGHTWEIGHT_CHECKPOINT_IMPL=${LIGHTWEIGHT_CHECKPOINT_IMPL} \ + -x USE_ASYNC_CHECKPOINTING=${USE_ASYNC_CHECKPOINTING} \ + -x LOG_DIR=${LOG_DIR} \ + -x TF_RECIPE_CACHE_PATH \ + -x DO_TRAIN=${DO_TRAIN} \ + -x DO_EVAL=${DO_EVAL} \ + -x EXPERIMENTAL_SLACK=${EXPERIMENTAL_SLACK} \ + -x NUM_DIST_EVAL_WORKERS=${NUM_DIST_EVAL_WORKERS} \ + -x WARMUP_STEPS=${WARMUP_STEPS} + -x AUX_PARAMS=${AUX_PARAMS} \ + -x TF_ENABLE_DYNAMIC_SHAPES=${TF_ENABLE_DYNAMIC_SHAPES} \ + -x OPTIMIZER=${OPTIMIZER} \ + -x SIGNALING_FROM_GRAPH=${SIGNALING_FROM_GRAPH} \ + ${BASE_PATH}/run.sh" + + echo "TRAINING COMMAND = ${TRAINING_COMMAND}" + printf "[launch_bert_hvd] Starting training...\n\n" + time $TRAINING_COMMAND |& tee -a $LOGFILE +fi +run_per_ip rm -rf $OUTPUT_DIR/*/model.ckpt-* +rm -rf $BASE_PATH/log +cp /root/build_log.csv ${OUTPUT_DIR}/ +cp ${MPI_HOSTFILE_PATH} ${OUTPUT_DIR}/ +cp -r $LOG_DIR/bert_log $BASE_PATH/log +cp $TF_RECIPE_CACHE_PATH/tf_bert_pretraining* ${OUTPUT_DIR}/ +chmod -R 777 ${OUTPUT_DIR} +exit $exit_code diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/HLS-Gaudi2-TF/run.sh b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/HLS-Gaudi2-TF/run.sh new file mode 100644 index 0000000000000000000000000000000000000000..ddd5e6ca31648b8ac7353a463fc09f37c19ac613 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/HLS-Gaudi2-TF/run.sh @@ -0,0 +1,164 @@ +#! /bin/bash + +#set -x +############################################################################### +# Copyright (C) 2020-2023 Habana Labs, Ltd. an Intel Company +# +############################################################################### + +SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) +export BASE_PATH="$( cd "$(dirname "$(readlink -f ${SCRIPT_DIR}/defaults.cfg)" )" && pwd)" +export PYTHONPATH=${BASE_PATH}:${BASE_PATH}/../TensorFlow/common + +PT_VERSION=`python3 -c 'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}")'` +TF_VERSION=`python3 -c "import tensorflow as tf; print(tf.__version__.replace('.', '_'))"` +PATCH_PATH=/usr/local/lib/python${PT_VERSION}/dist-packages/habana_frameworks/tensorflow/tf${TF_VERSION}/lib/habanalabs +export PYTHONPATH=${PATCH_PATH}:${PYTHONPATH} + +TRAIN_BATCH_SIZE=${TRAIN_BATCH_SIZE:-7} +EVAL_BATCH_SIZE=${EVAL_BATCH_SIZE:-125} +LEARNING_RATE=${LEARNING_RATE:-5e-5} +PRECISION=${PRECISION:-fp32} +WARMUP_STEPS=${WARMUP_STEPS:-0} +TRAIN_STEPS=${TRAIN_STEPS:-8103} +SAVE_CHECKPOINTS_STEPS=${SAVE_CHECKPOINTS_STEPS:-335} +NUM_ACCUMULATION_STEPS=${NUM_ACCUMULATION_STEPS:-4} +SAMPLES_BETWEEN_EVAL=${SAMPLES_BETWEEN_EVAL:-150080} +STOP_THRESHOLD=${STOP_THRESHOLD:-0.720} +SAMPLES_START_EVAL=${SAMPLES_START_EVAL:-3000000} +MAX_EVAL_STEPS=${MAX_EVAL_STEPS:-0} +IS_DIST_EVAL_ENABLED=${IS_DIST_EVAL_ENABLED:-false} +MAX_SEQ_LENGTH=${MAX_SEQ_LENGTH:-512} +MAX_PRED_PER_SEQ=${MAX_PRED_PER_SEQ:-76} +FAST_PERF_ONLY=${FAST_PERF_ONLY:-0} +PACKED_DATA=${PACKED_DATA:-False} +TESTDATE=${TESTDATE} +TESTTIME=${TESTTIME} +LAMB_BETA_1=${LAMB_BETA_1:-0.9} +LAMB_BETA_2=${LAMB_BETA_2:-0.999} +EPSILON=${EPSILON:-1e-6} +LAMB_WEIGHT_DECAY_RATE=${LAMB_WEIGHT_DECAY_RATE:-0.01} +LAMB_LEARNING_RATE_DECAY_POLY_POWER=${LAMB_LEARNING_RATE_DECAY_POLY_POWER:-1.0} +NUM_WORKERS_PER_HLS=${NUM_WORKERS_PER_HLS:-4} +DO_TRAIN=${DO_TRAIN:-True} +DO_EVAL=${DO_EVAL:-True} +EXPERIMENTAL_SLACK=${EXPERIMENTAL_SLACK:-True} +NUM_DIST_EVAL_WORKERS=${NUM_DIST_EVAL_WORKERS:-0} +OPTIMIZER=${OPTIMIZER:-'lamb'} + +export TF_BF16_CONVERSION=${BASE_PATH}/../TensorFlow/common/bf16_config/bert.json +export USE_LIGHTWEIGHT_CHECKPOINT=${USE_LIGHTWEIGHT_CHECKPOINT:-True} +export LIGHTWEIGHT_CHECKPOINT_IMPL=${LIGHTWEIGHT_CHECKPOINT_IMPL:-"basic"} +export USE_ASYNC_CHECKPOINTING=${USE_ASYNC_CHECKPOINTING:-False} +export BERT_CONFIG_FILE=${BERT_CONFIG_FILE:-${BERT_CONFIG_DIR}/bert_config.json} + +if [[ $SIGNALING_FROM_GRAPH -eq 1 ]]; then + export TF_DISABLE_SCOPED_ALLOCATOR=True + export HOROVOD_FUSION_THRESHOLD=0 + export TF_USE_SIGNALING_FROM_ENCAP_OP=1 +else + export TF_USE_SIGNALING_FROM_ENCAP_OP=0 +fi + +# Currently sharded LAMB works only when ScopedAllocator is disabled and loop unrolling is False +if [ $OPTIMIZER == "sharded_lamb" ]; then + export TF_DISABLE_SCOPED_ALLOCATOR=True + AUX_PARAMS="${AUX_PARAMS} --loop_unrolling_for_train_op=False" +fi + +# Under the hood, AMP (Arithmetic Mixed Precision) training is applied via TF_BF16_CONVERSION +# default precision is fp32. +precision="--noamp" + +USE_HOROVOD=${USE_HOROVOD:-"False"} +if [ $USE_HOROVOD == "True" ]; then + horovod="--horovod --allreduce_post_accumulation=True" + IS_DIST_EVAL_ENABLED="True" +else + horovod="" +fi + +#PHASE 1 Config +export PHASE1_CKPT=${PHASE1_CKPT:-/root/datasets/bert_pretraining/MLPerf_BERT_checkpoint/model.ckpt-28252} +export INPUT_FILES_DIR=${INPUT_FILES_DIR:-/root/datasets/bert_pretraining/training} +export EVAL_FILES_DIR=${EVAL_FILES_DIR:-/root/datasets/bert_pretraining/evaluation} + +#Generate Host Folder +if [ $USE_DRAM_OUTPUT == "True" ]; then + host=$(hostname) + if [ "$OMPI_COMM_WORLD_LOCAL_RANK" == "0" ]; then + mkdir -p /mnt/dramfs + mount -t tmpfs -o size=200g tmpfs /mnt/dramfs + fi + export OUTPUT_DIR=/mnt/dramfs/bert_gaudi${NUM_WORKERS_TOTAL}_${TESTDATE}_${TESTTIME}/${host} + mkdir -p $OUTPUT_DIR +fi + +# clear cache +if [[ $OMPI_COMM_WORLD_LOCAL_RANK -eq 0 ]]; then + PROC_FS=${PROC_FS:-"/proc"} + sync && echo 3 > $PROC_FS/sys/vm/drop_caches +fi + +if [ $PACKED_DATA == "False" ]; then + packing_arg="" +else + packing_arg="--enable_packed_data_mode --avg_seq_per_pack=2" +fi + +AUX_PARAMS=$(echo ${AUX_PARAMS} | sed s/:/\ /g) + +enable_device_warmup=True + +TRAIN_COMMAND="python3 ${BASE_PATH}/../TensorFlow/nlp/bert/run_pretraining.py \ + --input_files_dir=$INPUT_FILES_DIR \ + --init_checkpoint=$PHASE1_CKPT \ + --eval_files_dir=$EVAL_FILES_DIR\ + --output_dir=$OUTPUT_DIR \ + --bert_config_file=$BERT_CONFIG_FILE \ + --do_train=$DO_TRAIN \ + --do_eval=$DO_EVAL \ + --experimental_slack=$EXPERIMENTAL_SLACK \ + --is_dist_eval_enabled=$IS_DIST_EVAL_ENABLED \ + --train_batch_size=$TRAIN_BATCH_SIZE \ + --eval_batch_size=$EVAL_BATCH_SIZE \ + --max_eval_steps=$MAX_EVAL_STEPS \ + --max_seq_length=$MAX_SEQ_LENGTH \ + --max_predictions_per_seq=$MAX_PRED_PER_SEQ \ + --num_train_steps=$TRAIN_STEPS \ + --num_accumulation_steps=$NUM_ACCUMULATION_STEPS \ + --num_warmup_steps=$WARMUP_STEPS \ + --save_checkpoints_steps=$SAVE_CHECKPOINTS_STEPS \ + --learning_rate=$LEARNING_RATE \ + $horovod \ + $precision \ + $packing_arg \ + --enable_device_warmup=$enable_device_warmup \ + --samples_between_eval=$SAMPLES_BETWEEN_EVAL \ + --stop_threshold=$STOP_THRESHOLD \ + --samples_start_eval=$SAMPLES_START_EVAL \ + --beta_1=$LAMB_BETA_1 \ + --beta_2=$LAMB_BETA_2 \ + --epsilon=$EPSILON \ + --weight_decay_rate=$LAMB_WEIGHT_DECAY_RATE \ + --power=$LAMB_LEARNING_RATE_DECAY_POLY_POWER \ + --enable_habana_backend \ + --dllog_path=$LOG_DIR/bert_dllog.json \ + --use_lightweight_checkpoint=$USE_LIGHTWEIGHT_CHECKPOINT \ + --lightweight_checkpoint_impl=$LIGHTWEIGHT_CHECKPOINT_IMPL \ + --use_async_checkpointing=$USE_ASYNC_CHECKPOINTING \ + --num_dist_eval_workers=$NUM_DIST_EVAL_WORKERS \ + --optimizer_type=$OPTIMIZER \ + ${AUX_PARAMS} +" + +LD_PRELOAD=${PRELOAD_PATH} ${TRAIN_COMMAND} + +if [[ $OMPI_COMM_WORLD_LOCAL_RANK == "0" ]]; then + rm -rf $OUTPUT_DIR/*/model.ckpt-* + rm -rf $OUTPUT_DIR/*/checkpoint + if [[ $USE_DRAM_OUTPUT == "True" ]]; then + cp -r $LOG_DIR/result_* /root/scratch/bert/bert_gaudi${NUM_WORKERS_TOTAL}_${TESTDATE}_${TESTTIME} + rm -rf /mnt/dramfs/bert_gaudi${NUM_WORKERS_TOTAL}_${TESTDATE}_${TESTTIME} + fi +fi diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/bf16_config/bert.json b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/bf16_config/bert.json new file mode 100644 index 0000000000000000000000000000000000000000..7cf83d0393ed82d77606f4c8d5902ddeb86f23bf --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/bf16_config/bert.json @@ -0,0 +1,57 @@ +{ + "allowlist": [ + "_ScopedAllocatorSplit", + "_ScopedAllocatorConcat", + "_ScopedAllocator", + "BatchMatMul", + "BatchMatMulV2", + "BiasAdd", + "BiasAddGrad", + "EuclideanNorm", + "Exp", + "HabanaDropout", + "HabanaDropoutGrad", + "HabanaDropoutStateful", + "HabanaGelu", + "HabanaGeluGrad", + "HabanaLayerNorm", + "HabanaLayerNormV2", + "HabanaLayerNormGrad", + "HabanaLayerNormGradV2", + "HabanaMaskedSoftmax", + "HabanaSoftmaxGrad", + "HabanaLogSoftmaxGrad", + "HorovodAllreduce", + "L2Loss", + "Log", + "LogSoftmax", + "MatMul", + "Softmax", + "Sum", + "Tanh", + "TanhGrad" + ], + "conditional_list": [ + "Add", + "AddV2", + "AddN", + "ExpandDims", + "Identity", + "Reshape", + "Slice", + "Split", + "StridedSliceGrad", + "Transpose" + ], + "strict_conditional_list": [], + "non_convertible_exceptions": [ + [".*KEEP_FP32_PRECISION.*", ""] + ], + "convertible_exceptions": [ + ["bert/encoder/layer_[0-9]+/attention/self/add", "AddV2"], + ["bert/encoder/layer_[0-9]+/attention/self/Mul", "Mul"], + ["clip_by_global_norm/mul", "Mul"], + ["global_norm/mul", "Mul"], + ["global_norm/global_norm", "Sqrt"] + ] +} \ No newline at end of file diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/common.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/common.py new file mode 100644 index 0000000000000000000000000000000000000000..216ed1ce22dff8b017d3c4404045bfca3117d00b --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/common.py @@ -0,0 +1,37 @@ +############################################################################### +# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company +############################################################################### + +import os +import logging +import subprocess +import sys +_log = logging.getLogger(__file__) + + +def setup_jemalloc() -> None: + """ + Setup libjemalloc.so.1 or libjemalloc.so.1 (depending on the OS version) + by exporting LD_PRELOAD env variable. + """ + _log.info("libjemalloc.so has been requested") + paths = {"LD_LIBRARY_PATH"} + env_vals = [os.environ[x] for x in paths if os.environ.get(x) is not None] + env_vals.extend(["/usr/lib/x86_64-linux-gnu"]) + sep = ":" + final_path = None + locations = sep.join(env_vals).split(sep) + for path in locations: + if path: + libpath = f"{path}/libjemalloc.so.1" + if os.path.isfile(libpath): + final_path = os.path.realpath(libpath) + for path in locations: + if path: + libpath = f"{path}/libjemalloc.so.2" + if os.path.isfile(libpath): + final_path = os.path.realpath(libpath) + if final_path: + os.environ["LD_PRELOAD"] = f"{final_path}:{os.environ.get('LD_PRELOAD', '')}" + else: + raise FileExistsError("Neither libjemalloc.so.1 nor libjemalloc.so.2 found.") diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/debug.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/debug.py new file mode 100644 index 0000000000000000000000000000000000000000..cbba13a582d557f4f6fe3f6e376d4d88f17ec069 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/debug.py @@ -0,0 +1,132 @@ +# Copyright 2019 The TensorFlow Authors. 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 (C) 2020-2021 Habana Labs, Ltd. an Intel Company +############################################################################### + +from absl import flags +from absl import logging +from tensorflow.core.protobuf import debug_event_pb2 +from tensorflow.python.debug.lib import debug_events_writer +from tensorflow.python.framework import op_callbacks +from tensorflow.python.ops import gen_debug_ops +import tensorflow as tf +import re +import os +import json + +try: + import horovod.tensorflow as hvd +except ImportError: + hvd = None + + +flags.DEFINE_string(name='dump_config', default=None, + help='Defines config for tensor dumping') + + +class _DumpCallback(object): + def __init__(self, dump_root, tensor_debug_mode, circular_buffer_size, op_regex, output_regex=None): + self._dump_root = dump_root + if hvd is not None and hvd.is_initialized(): + self._dump_root = os.path.join( + self._dump_root, f"rank_{hvd.rank()}") + self._tensor_debug_mode = debug_event_pb2.TensorDebugMode.Value( + tensor_debug_mode) + self._circular_buffer_size = circular_buffer_size + self._op_regex = re.compile(op_regex) if isinstance( + op_regex, str) else op_regex + self._output_regex = re.compile(output_regex) if isinstance( + output_regex, str) else output_regex + self._tfdbg_run_id = '' + self._dump_op_counter = 0 + + debug_writer_args = { + "dump_root": self._dump_root, + "circular_buffer_size": self._circular_buffer_size + } + + if not tf.__version__.startswith("2.2"): + debug_writer_args["tfdbg_run_id"] = self._tfdbg_run_id + + self._writer = debug_events_writer.DebugEventsWriter( + **debug_writer_args) + + def callback(self, op_type, inputs, attrs, outputs, op_name=None, graph=None): + if op_name is not None and self._op_regex.match(op_name): + graph_name = "missing-graph-name" + if graph is not None and hasattr(graph, "name"): + graph_name = graph.name + + logging.info("Adding dump op for '%s' of type '%s' from graph '%s'" % ( + op_name, op_type, graph_name)) + + new_outputs = [] + + for output_slot, output in enumerate(outputs): + if self._output_regex is not None and not self._output_regex.match(output.name): + logging.info("Skipped output: " + output.name) + new_outputs.append(output) + continue + debug_identity_op_kwargs = { + "tfdbg_context_id": graph_name, + "op_name": op_name, + "output_slot": output_slot, + "tensor_debug_mode": self._tensor_debug_mode, + "debug_urls": ["file://%s" % self._dump_root], + "name": "dump_%d" % self._dump_op_counter + } + + if not tf.__version__.startswith("2.2"): + debug_identity_op_kwargs["circular_buffer_size"] = self._circular_buffer_size + debug_identity_op_kwargs["tfdbg_run_id"] = self._tfdbg_run_id + + self._dump_op_counter = self._dump_op_counter + 1 + new_outputs.append(gen_debug_ops.debug_identity_v2( + output, **debug_identity_op_kwargs)) + + return new_outputs + else: + return None + + def __enter__(self, *args, **kwargs): + op_callbacks.add_op_callback(self.callback) + logging.info("Enabled tensor dumping") + + def __exit__(self, *args, **kwargs): + op_callbacks.remove_op_callback(self.callback) + logging.info("Disabled tensor dumping") + + def __del__(self): + self._writer.Close() + + +class _Dummy(object): + def __enter__(self, *args, **kwargs): + pass + + def __exit__(self, *args, **kwargs): + pass + + +def dump_callback(config_file=None): + if config_file is not None: + kwargs = json.load(open(config_file, 'r')) + return _DumpCallback(**kwargs) + try: + kwargs = json.load(open(flags.FLAGS.dump_config, 'r')) + return _DumpCallback(**kwargs) + except: + return _Dummy() diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/horovod_helpers_gpu.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/horovod_helpers_gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..10b628d5415eb4b871817cd35bc25b2d0e70e925 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/horovod_helpers_gpu.py @@ -0,0 +1,23 @@ +import os +import horovod.tensorflow as hvd + +def hvd_init(): + hvd.init() + +def hvd_size(): + return hvd.size() + +def hvd_rank(): + return hvd.rank() + +def comm_size(): + return int(os.environ.get("OMPI_COMM_WORLD_SIZE", 1)) + +def horovod_enabled(): + try: + return hvd.size() > 1 + except ValueError: + return False + +def comm_local_rank(): + return int(os.environ.get("OMPI_COMM_WORLD_LOCAL_RANK", 0)) \ No newline at end of file diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/modeling/performance.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/modeling/performance.py new file mode 100644 index 0000000000000000000000000000000000000000..4b264f53256db66326ee4e51c5a29676e273eca9 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/modeling/performance.py @@ -0,0 +1,56 @@ +# Lint as: python3 +# Copyright 2020 The TensorFlow Authors. 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. +# ============================================================================== +"""Functions and classes related to training performance.""" + +import tensorflow as tf + + +def configure_optimizer(optimizer, + use_float16=False, + use_graph_rewrite=False, + loss_scale="dynamic"): + """Configures optimizer object with performance options.""" + if use_float16: + # Wraps optimizer with a LossScaleOptimizer. This is done automatically + # in compile() with the "mixed_float16" policy, but since we do not call + # compile(), we must wrap the optimizer manually. + optimizer = ( + tf.keras.mixed_precision.experimental.LossScaleOptimizer( + optimizer, loss_scale=loss_scale)) + if use_graph_rewrite: + # Note: the model dtype must be 'float32', which will ensure + # tf.ckeras.mixed_precision and + # tf.train.experimental.enable_mixed_precision_graph_rewrite do not double + # up. + optimizer = tf.train.experimental.enable_mixed_precision_graph_rewrite( + optimizer) + return optimizer + + +def set_mixed_precision_policy(dtype, loss_scale=None): + """Sets mix precision policy.""" + if dtype == tf.float16: + policy = tf.keras.mixed_precision.experimental.Policy( + 'mixed_float16', loss_scale=loss_scale) + tf.keras.mixed_precision.experimental.set_policy(policy) + elif dtype == tf.bfloat16: + policy = tf.keras.mixed_precision.experimental.Policy( + 'mixed_bfloat16') + tf.keras.mixed_precision.experimental.set_policy(policy) + elif dtype == tf.float32: + tf.keras.mixed_precision.experimental.set_policy('float32') + else: + raise ValueError("Unexpected dtype: %s" % dtype) diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/modeling/tf_utils.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/modeling/tf_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c98743509bbf83f0253575964c5a5aa32d902101 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/modeling/tf_utils.py @@ -0,0 +1,175 @@ +# Copyright 2019 The TensorFlow Authors. 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. +# ============================================================================== +"""Common TF utilities.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import six +import tensorflow as tf + +from tensorflow.python.util import deprecation +from TensorFlow.common.modeling import activations + + +@deprecation.deprecated( + None, + "tf.keras.layers.Layer supports multiple positional args and kwargs as " + "input tensors. pack/unpack inputs to override __call__ is no longer " + "needed." +) +def pack_inputs(inputs): + """Pack a list of `inputs` tensors to a tuple. + + Args: + inputs: a list of tensors. + + Returns: + a tuple of tensors. if any input is None, replace it with a special constant + tensor. + """ + inputs = tf.nest.flatten(inputs) + outputs = [] + for x in inputs: + if x is None: + outputs.append(tf.constant(0, shape=[], dtype=tf.int32)) + else: + outputs.append(x) + return tuple(outputs) + + +@deprecation.deprecated( + None, + "tf.keras.layers.Layer supports multiple positional args and kwargs as " + "input tensors. pack/unpack inputs to override __call__ is no longer " + "needed." +) +def unpack_inputs(inputs): + """unpack a tuple of `inputs` tensors to a tuple. + + Args: + inputs: a list of tensors. + + Returns: + a tuple of tensors. if any input is a special constant tensor, replace it + with None. + """ + inputs = tf.nest.flatten(inputs) + outputs = [] + for x in inputs: + if is_special_none_tensor(x): + outputs.append(None) + else: + outputs.append(x) + x = tuple(outputs) + + # To trick the very pointless 'unbalanced-tuple-unpacking' pylint check + # from triggering. + if len(x) == 1: + return x[0] + return tuple(outputs) + + +def is_special_none_tensor(tensor): + """Checks if a tensor is a special None Tensor.""" + return tensor.shape.ndims == 0 and tensor.dtype == tf.int32 + + +# TODO(hongkuny): consider moving custom string-map lookup to keras api. +def get_activation(identifier): + """Maps a identifier to a Python function, e.g., "relu" => `tf.nn.relu`. + + It checks string first and if it is one of customized activation not in TF, + the corresponding activation will be returned. For non-customized activation + names and callable identifiers, always fallback to tf.keras.activations.get. + + Args: + identifier: String name of the activation function or callable. + + Returns: + A Python function corresponding to the activation function. + """ + if isinstance(identifier, six.string_types): + name_to_fn = { + "gelu": activations.gelu, + "simple_swish": activations.simple_swish, + "hard_swish": activations.hard_swish, + "identity": activations.identity, + } + identifier = str(identifier).lower() + if identifier in name_to_fn: + return tf.keras.activations.get(name_to_fn[identifier]) + return tf.keras.activations.get(identifier) + + +def get_shape_list(tensor, expected_rank=None, name=None): + """Returns a list of the shape of tensor, preferring static dimensions. + + Args: + tensor: A tf.Tensor object to find the shape of. + expected_rank: (optional) int. The expected rank of `tensor`. If this is + specified and the `tensor` has a different rank, and exception will be + thrown. + name: Optional name of the tensor for the error message. + + Returns: + A list of dimensions of the shape of tensor. All static dimensions will + be returned as python integers, and dynamic dimensions will be returned + as tf.Tensor scalars. + """ + if expected_rank is not None: + assert_rank(tensor, expected_rank, name) + + shape = tensor.shape.as_list() + + non_static_indexes = [] + for (index, dim) in enumerate(shape): + if dim is None: + non_static_indexes.append(index) + + if not non_static_indexes: + return shape + + dyn_shape = tf.shape(tensor) + for index in non_static_indexes: + shape[index] = dyn_shape[index] + return shape + + +def assert_rank(tensor, expected_rank, name=None): + """Raises an exception if the tensor rank is not of the expected rank. + + Args: + tensor: A tf.Tensor to check the rank of. + expected_rank: Python integer or list of integers, expected rank. + name: Optional name of the tensor for the error message. + + Raises: + ValueError: If the expected shape doesn't match the actual shape. + """ + expected_rank_dict = {} + if isinstance(expected_rank, six.integer_types): + expected_rank_dict[expected_rank] = True + else: + for x in expected_rank: + expected_rank_dict[x] = True + + actual_rank = tensor.shape.ndims + if actual_rank not in expected_rank_dict: + raise ValueError( + "For the tensor `%s`, the actual tensor rank `%d` (shape = %s) is not " + "equal to the expected tensor rank `%s`" % + (name, actual_rank, str(tensor.shape), str(expected_rank))) diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/tb_utils.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/tb_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9873ebb0838f3b0bc9c20e5924b93e0a72245e42 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/tb_utils.py @@ -0,0 +1,259 @@ +import os +import time +import tensorflow as tf +from copy import deepcopy +from tensorboard.plugins.hparams import api as hp +from tensorflow.python.eager import context +from tensorflow.keras import backend as K +from tensorflow.python.ops import summary_ops_v2 +from tensorflow.python.summary import summary as tf_summary +from tensorflow.python.training.summary_io import SummaryWriterCache +from tensorflow.compat.v1.keras.callbacks import TensorBoard, Callback + + +def _remove_prefix(s, prefix): + if s.startswith(prefix): + s = s[len(prefix):] + return s + + +def _parse_precision(): + flag = os.environ.get('TF_BF16_CONVERSION', '0') + flag = flag.lower() + try: + value = int(flag) + except: + value = -1 + + if flag == 'false' or value == 0: + return 'fp32' + elif flag == 'true' or value == 1: + return 'bf16' + return flag + + +def _set_precision_if_missing(hparams: dict): + if 'precision' not in hparams: + hparams['precision'] = _parse_precision() + return hparams + + +def _copy_and_clean_hparams(hparams: dict): + hparams_ = dict() + for name, value in hparams.items(): + if isinstance(value, (str, bool, int, float)): + hparams_[name] = value + continue + + try: + hparams_[name] = str(value) + tf.compat.v1.logging.info( + f'Type of parameter "{name}" is not one of (bool, int, float, str). ' + 'It will be saved as a string.') + except: + tf.compat.v1.logging.info( + f'Conversion of parameter "{name}" to string failed. ' + 'Parameter will not be saved.') + + return hparams_ + + +def write_hparams_v1(writer, hparams: dict): + hparams = _copy_and_clean_hparams(hparams) + hparams = _set_precision_if_missing(hparams) + + # We create Session here, because in case of older topologies + # that run in graph mode the FileWriter needs it. + with tf.compat.v1.Session(): + if isinstance(writer, str): + writer = SummaryWriterCache.get(writer) + summary = hp.hparams_pb(hparams).SerializeToString() + writer.add_summary(summary) + + +def write_hparams_v2(writer, hparams: dict): + hparams = _copy_and_clean_hparams(hparams) + hparams = _set_precision_if_missing(hparams) + + with writer.as_default(): + hp.hparams(hparams) + + +class ExamplesPerSecondEstimatorHook(tf.compat.v1.train.StepCounterHook): + """Calculate and report global_step/sec and examples/sec during runtime.""" + # Copy-pasted from tensorflow_estimator/python/estimator/tpu/tpu_estimator.py + + def __init__(self, + batch_size=None, + every_n_steps=1, + every_n_secs=None, + output_dir=None, + summary_writer=None, + extra_metrics=None, + verbose=False): + super().__init__( + every_n_steps=every_n_steps, + every_n_secs=every_n_secs, + output_dir=output_dir, + summary_writer=summary_writer) + self._extra_metrics = extra_metrics or {} + self._verbose = verbose + if batch_size is not None: + self._extra_metrics['examples/sec'] = batch_size + + def _add_summary(self, tag, value, step): + Summary = tf.compat.v1.Summary + global_step_summary = Summary(value=[ + Summary.Value(tag=tag, simple_value=value) + ]) + self._summary_writer.add_summary(global_step_summary, step) + if self._verbose: + tf.compat.v1.logging.info(f'{tag}: {value}') + + def _log_and_record(self, elapsed_steps, elapsed_time, global_step): + global_step_per_sec = elapsed_steps / elapsed_time + if self._summary_writer is not None: + self._add_summary('global_step/sec', + global_step_per_sec, global_step) + for name, factor in self._extra_metrics.items(): + value = factor * global_step_per_sec + self._add_summary(name, value, global_step) + + +class ExamplesPerSecondKerasHook(Callback): + def __init__(self, + every_n_steps=1, + every_n_secs=None, + output_dir=None, + summary_writer=None): + self.writer = summary_writer or SummaryWriterCache.get(output_dir) + self._timer = tf.compat.v1.train.SecondOrStepTimer( + every_n_secs, every_n_steps) + self._total_examples = 0 + self._should_trigger = True + + def on_train_begin(self, logs=None): + self._timer.reset() + + def on_train_batch_begin(self, batch, logs=None): + self._should_trigger = self._timer.should_trigger_for_step( + logs.get('batch', 0)) + + def on_train_batch_end(self, batch, logs=None): + step = logs.get('batch', 0) + self._total_examples += logs.get('size', 0) + if self._should_trigger: + elapsed_time, elapsed_steps = self._timer.update_last_triggered_step( + step) + if elapsed_time is not None: + self._log_and_record( + elapsed_steps, elapsed_time, step, self._total_examples) + self._total_examples = 0 + + def _log_and_record(self, elapsed_steps, elapsed_time, + global_step, total_examples=None): + Summary = tf.compat.v1.Summary + global_step_per_sec = elapsed_steps / elapsed_time + if self.writer is not None: + global_step_summary = Summary(value=[ + Summary.Value( + tag='global_step/sec', simple_value=global_step_per_sec) + ]) + self.writer.add_summary(global_step_summary, global_step) + if total_examples is not None: + examples_per_sec = total_examples / elapsed_time + example_summary = Summary(value=[ + Summary.Value(tag='examples/sec', + simple_value=examples_per_sec) + ]) + self.writer.add_summary(example_summary, global_step) + + +class TBSummary(object): + """ + Creates a proxy for FileWriter for TensorBoard. + + :param log_dir: - path where experiment is running (usually the same as + model_dir in Estimator) + """ + + def __init__(self, log_dir: str): + super().__init__() + self._log_dir = log_dir + self._session = None + + def __enter__(self): + self._session = tf.compat.v1.Session() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._session: + self._session.close() + self._session = None + + def add_scalar(self, tag, value, global_step=None): + with self._session: + writer = SummaryWriterCache.get(self._log_dir) + summary = tf.compat.v1.Summary( + value=[tf.compat.v1.Summary.Value(tag=tag, simple_value=value)]) + event = tf.compat.v1.Event(summary=summary) + event.wall_time = time.time() + event.step = global_step + writer.add_event(event) + + +class TensorBoardWithHParamsV1(TensorBoard): + """ + Adds TensorBoard visualization to training process. + + Writes training tfevent file into default log directory, but + stores evaluation in log_dir/eval subdirectory. + """ + + def __init__(self, hparams, *args, **kwargs): + super().__init__(*args, **kwargs) + self.hparams = hparams + self._train_writer = None + self._eval_writer = None + + def _switch_writer(self, mode): + self.writer = self._train_writer if mode == 'train' else self._eval_writer + + def _init_writer(self, model): + """Sets file writer.""" + if context.executing_eagerly(): + raise NotImplementedError('hook does not support eager execution') + + self._train_writer = SummaryWriterCache.get(self.log_dir) + self._eval_writer = SummaryWriterCache.get( + os.path.join(self.log_dir, 'eval')) + self._switch_writer('train') + + write_hparams_v1(self.writer, self.hparams) + + def _write_custom_summaries(self, step, logs=None): + """ + This methods works on the assumption that metrics containing `val` + in name are related to validation (that's the default in Keras). + """ + + logs = logs or {} + train_logs = {} + eval_logs = {} + + for name, value in logs.items(): + if 'val' in name: + if name.startswith('batch_val_'): + name = 'batch_' + _remove_prefix(name, 'batch_val_') + elif name.startswith('epoch_val_'): + name = _remove_prefix(name, 'epoch_val_') + eval_logs[name] = value + else: + if name.startswith('batch_'): + name = _remove_prefix(name, 'batch_') + train_logs[name] = value + + self._switch_writer('eval') + super()._write_custom_summaries(step, eval_logs) + self._switch_writer('train') + super()._write_custom_summaries(step, train_logs) diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/utils.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2126c7c505b68ebbcaa63293fab73cd341451d2a --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/utils.py @@ -0,0 +1,105 @@ +# ****************************************************************************** +# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company +# ****************************************************************************** + +import logging +import os +import sys +from contextlib import contextmanager +from tensorflow.python.training.session_run_hook import SessionRunHook, SessionRunArgs + +import tensorflow as tf +from tensorflow.python.training import training_util +from tensorflow.core.protobuf import config_pb2 +from tensorflow.python.client import timeline +from tensorflow.python.platform import gfile + +@contextmanager +def disable_session_recovery(): + """ Disable session recovery on backend errors. + + MonitoredSession that is used by Estimator hard-codes that AbortedError + and UnavailableError should not terminate but instead silently restart + training. This constitutes a broad list of c++ backend errors, including + OOM, that may cause endless error/restart loop. + """ + from tensorflow.python.training import training + module= sys.modules['tensorflow.python.training.monitored_session'] + ignored_error_list_attr = "_PREEMPTION_ERRORS" + orig_ignored_errors = getattr(module, ignored_error_list_attr) + setattr(module, ignored_error_list_attr, tuple()) + yield + setattr(module, ignored_error_list_attr, orig_ignored_errors) + + +class RangeTFChromeProfilerHook(tf.compat.v1.estimator.SessionRunHook): + + def __init__(self, + start_iter=None, + num_iters=None, + output_dir="."): + self._start_iter=start_iter + self._end_iter=start_iter+num_iters + self._curr_iter=0 + self._output_dir=output_dir + self._metadata=[] + + def before_run(self, run_context): + self._curr_iter=self._curr_iter+1 + if self._curr_iter > self._start_iter and self._curr_iter <= self._end_iter: + return tf.estimator.SessionRunArgs(None, options=config_pb2.RunOptions(trace_level=config_pb2.RunOptions.FULL_TRACE)) + else: + return None + + def after_run(self, run_context, run_values): + if self._curr_iter > self._start_iter and self._curr_iter <= self._end_iter: + self._metadata.append(run_values.run_metadata.step_stats) + + if self._curr_iter == self._end_iter: + self._save(self._curr_iter, self._output_dir) + run_context.request_stop() + + def _save(self, step, save_path): + logging.info("Saving timeline for %d into '%s'.", step, save_path) + if not os.path.exists(save_path): + os.makedirs(save_path) + + traces=self._metadata[0] + for ds in self._metadata[1:]: + traces.dev_stats.MergeFrom(ds.dev_stats) + + with gfile.Open("{}/tf_trace.json".format(save_path), "w") as f: + trace = timeline.Timeline(traces) + f.write( + trace.generate_chrome_trace_format(show_dataflow=False, show_memory=False)) + + +class RangeTFHltvProfilerHook(SessionRunHook): + def __init__(self, + output_dir="", + profile_steps="" + ): + self.output_dir = output_dir + profile_steps_error_message = ( + 'profile_steps must be a comma separated pair of positive integers, ' + 'specifying the first and last steps to be profiled.' + ) + try: + profile_steps = [int(i) for i in profile_steps.split(',')] + except ValueError: + raise ValueError(profile_steps_error_message) + if len(profile_steps) != 2: + raise ValueError(profile_steps_error_message) + self.start_step, self.stop_step = profile_steps + if self.start_step < 0 or self.start_step > self.stop_step: + raise ValueError(profile_steps_error_message) + self._step=0 + + def before_run(self, run_context): + if self._step == self.start_step: + tf.profiler.experimental.start(self.output_dir) + elif self._step == self.stop_step+1: + tf.profiler.experimental.stop() + + self._step = self._step + 1 + return SessionRunArgs({}) \ No newline at end of file diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/README.md b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/README.md new file mode 100644 index 0000000000000000000000000000000000000000..65ee55854f0051af6d4c763fe7003ffecfb81e24 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/README.md @@ -0,0 +1,97 @@ +# Adding Abseil (absl) flags quickstart +## Defining a flag +absl flag definitions are similar to argparse, although they are defined on a global namespace. + +For instance defining a string flag looks like: +```$xslt +from absl import flags +flags.DEFINE_string( + name="my_flag", + default="a_sensible_default", + help="Here is what this flag does." +) +``` + +All three arguments are required, but default may be `None`. A common optional argument is +short_name for defining abreviations. Certain `DEFINE_*` methods will have other required arguments. +For instance `DEFINE_enum` requires the `enum_values` argument to be specified. + +## Key Flags +absl has the concept of a key flag. Any flag defined in `__main__` is considered a key flag by +default. Key flags are displayed in `--help`, others only appear in `--helpfull`. In order to +handle key flags that are defined outside the module in question, absl provides the +`flags.adopt_module_key_flags()` method. This adds the key flags of a different module to one's own +key flags. For example: +```$xslt +File: flag_source.py +--------------------------------------- + +from absl import flags +flags.DEFINE_string(name="my_flag", default="abc", help="a flag.") +``` + +```$xslt +File: my_module.py +--------------------------------------- + +from absl import app as absl_app +from absl import flags + +import flag_source + +flags.adopt_module_key_flags(flag_source) + +def main(_): + pass + +absl_app.run(main, [__file__, "-h"] +``` + +when `my_module.py` is run it will show the help text for `my_flag`. Because not all flags defined +in a file are equally important, `official/utils/flags/core.py` (generally imported as flags_core) +provides an abstraction for handling key flag declaration in an easy way through the +`register_key_flags_in_core()` function, which allows a module to make a single +`adopt_key_flags(flags_core)` call when using the util flag declaration functions. + +## Validators +Often the constraints on a flag are complicated. absl provides the validator decorator to allow +one to mark a function as a flag validation function. Suppose we want users to provide a flag +which is a palindrome. + +```$xslt +from absl import flags + +flags.DEFINE_string(name="pal_flag", short_name="pf", default="", help="Give me a palindrome") + +@flags.validator("pal_flag") +def _check_pal(provided_pal_flag): + return provided_pal_flag == provided_pal_flag[::-1] + +``` + +Validators take the form that returning True (truthy) passes, and all others +(False, None, exception) fail. + +## Testing +To test using absl, simply declare flags in the setupClass method of TensorFlow's TestCase. + +```$xslt +from absl import flags +import tensorflow as tf + +def define_flags(): + flags.DEFINE_string(name="test_flag", default="abc", help="an example flag") + + +class BaseTester(unittest.TestCase): + + @classmethod + def setUpClass(cls): + super(BaseTester, cls).setUpClass() + define_flags() + + def test_trivial(self): + flags_core.parse_flags([__file__, "test_flag", "def"]) + self.AssertEqual(flags.FLAGS.test_flag, "def") + +``` diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/__init__.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/_base.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..93e9586c4de519d6af71aa6dc1c0094d3686d5bb --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/_base.py @@ -0,0 +1,163 @@ +# Copyright 2018 The TensorFlow Authors. 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. +# ============================================================================== +"""Flags which will be nearly universal across models.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from absl import flags +import tensorflow as tf + +from TensorFlow.utils.flags._conventions import help_wrap +from TensorFlow.utils.logs import hooks_helper + + +def define_base(data_dir=True, model_dir=True, clean=False, train_epochs=False, + epochs_between_evals=False, stop_threshold=False, + batch_size=True, num_gpu=False, hooks=False, export_dir=False, + distribution_strategy=False, run_eagerly=False): + """Register base flags. + + Args: + data_dir: Create a flag for specifying the input data directory. + model_dir: Create a flag for specifying the model file directory. + clean: Create a flag for removing the model_dir. + train_epochs: Create a flag to specify the number of training epochs. + epochs_between_evals: Create a flag to specify the frequency of testing. + stop_threshold: Create a flag to specify a threshold accuracy or other + eval metric which should trigger the end of training. + batch_size: Create a flag to specify the batch size. + num_gpu: Create a flag to specify the number of GPUs used. + hooks: Create a flag to specify hooks for logging. + export_dir: Create a flag to specify where a SavedModel should be exported. + distribution_strategy: Create a flag to specify which Distribution Strategy + to use. + run_eagerly: Create a flag to specify to run eagerly op by op. + Returns: + A list of flags for core.py to marks as key flags. + """ + key_flags = [] + + if data_dir: + flags.DEFINE_string( + name="data_dir", short_name="dd", default="/tmp", + help=help_wrap("The location of the input data.")) + key_flags.append("data_dir") + + if model_dir: + flags.DEFINE_string( + name="model_dir", short_name="md", default="/tmp", + help=help_wrap("The location of the model checkpoint files.")) + key_flags.append("model_dir") + + if clean: + flags.DEFINE_boolean( + name="clean", default=False, + help=help_wrap("If set, model_dir will be removed if it exists.")) + key_flags.append("clean") + + if train_epochs: + flags.DEFINE_integer( + name="train_epochs", short_name="te", default=1, + help=help_wrap("The number of epochs used to train.")) + key_flags.append("train_epochs") + + if epochs_between_evals: + flags.DEFINE_integer( + name="epochs_between_evals", short_name="ebe", default=1, + help=help_wrap("The number of training epochs to run between " + "evaluations.")) + key_flags.append("epochs_between_evals") + + if stop_threshold: + flags.DEFINE_float( + name="stop_threshold", short_name="st", + default=None, + help=help_wrap("If passed, training will stop at the earlier of " + "train_epochs and when the evaluation metric is " + "greater than or equal to stop_threshold.")) + + if batch_size: + flags.DEFINE_integer( + name="batch_size", short_name="bs", default=32, + help=help_wrap("Batch size for training and evaluation. When using " + "multiple gpus, this is the global batch size for " + "all devices. For example, if the batch size is 32 " + "and there are 4 GPUs, each GPU will get 8 examples on " + "each step.")) + key_flags.append("batch_size") + + if num_gpu: + flags.DEFINE_integer( + name="num_gpus", short_name="ng", + default=1, + help=help_wrap( + "How many GPUs to use at each worker with the " + "DistributionStrategies API. The default is 1.")) + + if run_eagerly: + flags.DEFINE_boolean( + name="run_eagerly", default=False, + help="Run the model op by op without building a model function.") + + if hooks: + # Construct a pretty summary of hooks. + hook_list_str = ( + u"\ufeff Hook:\n" + u"\n".join([u"\ufeff {}".format(key) for key + in hooks_helper.HOOKS])) + flags.DEFINE_list( + name="hooks", short_name="hk", default="LoggingTensorHook", + help=help_wrap( + u"A list of (case insensitive) strings to specify the names of " + u"training hooks.\n{}\n\ufeff Example: `--hooks ProfilerHook," + u"ExamplesPerSecondHook`\n See official.utils.logs.hooks_helper " + u"for details.".format(hook_list_str)) + ) + key_flags.append("hooks") + + if export_dir: + flags.DEFINE_string( + name="export_dir", short_name="ed", default=None, + help=help_wrap("If set, a SavedModel serialization of the model will " + "be exported to this directory at the end of training. " + "See the README for more details and relevant links.") + ) + key_flags.append("export_dir") + + if distribution_strategy: + flags.DEFINE_string( + name="distribution_strategy", short_name="ds", default="mirrored", + help=help_wrap("The Distribution Strategy to use for training. " + "Accepted values are 'off', 'one_device', " + "'mirrored', 'parameter_server', 'collective', " + "case insensitive. 'off' means not to use " + "Distribution Strategy; 'default' means to choose " + "from `MirroredStrategy` or `OneDeviceStrategy` " + "according to the number of GPUs.") + ) + + + return key_flags + + +def get_num_gpus(flags_obj): + """Treat num_gpus=-1 as 'use all'.""" + if flags_obj.num_gpus != -1: + return flags_obj.num_gpus + + from tensorflow.python.client import device_lib # pylint: disable=g-import-not-at-top + local_device_protos = device_lib.list_local_devices() + return sum([1 for d in local_device_protos if d.device_type == "GPU"]) diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/_conventions.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/_conventions.py new file mode 100644 index 0000000000000000000000000000000000000000..81ad21b0c4c9a58fb7aa40402ae91c62a4c51352 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/_conventions.py @@ -0,0 +1,54 @@ +# Copyright 2018 The TensorFlow Authors. 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. +# ============================================================================== +"""Central location for shared argparse convention definitions.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import sys +import codecs +import functools + +from absl import app as absl_app +from absl import flags + + +# This codifies help string conventions and makes it easy to update them if +# necessary. Currently the only major effect is that help bodies start on the +# line after flags are listed. All flag definitions should wrap the text bodies +# with help wrap when calling DEFINE_*. +_help_wrap = functools.partial(flags.text_wrap, length=80, indent="", + firstline_indent="\n") + + +# Pretty formatting causes issues when utf-8 is not installed on a system. +def _stdout_utf8(): + try: + codecs.lookup("utf-8") + except LookupError: + return False + return sys.stdout.encoding == "UTF-8" + + +if _stdout_utf8(): + help_wrap = _help_wrap +else: + def help_wrap(text, *args, **kwargs): + return _help_wrap(text, *args, **kwargs).replace(u"\ufeff", u"") + + +# Replace None with h to also allow -h +absl_app.HelpshortFlag.SHORT_NAME = "h" diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/_device.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/_device.py new file mode 100644 index 0000000000000000000000000000000000000000..e91a09a3dbba2c9a2dd9bc9f5045f00cd12902d7 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/_device.py @@ -0,0 +1,85 @@ +# Copyright 2018 The TensorFlow Authors. 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. +# ============================================================================== +"""Flags for managing compute devices. Currently only contains TPU flags.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from absl import flags +import tensorflow as tf + +from TensorFlow.utils.flags._conventions import help_wrap + + +def require_cloud_storage(flag_names): + """Register a validator to check directory flags. + Args: + flag_names: An iterable of strings containing the names of flags to be + checked. + """ + msg = "TPU requires GCS path for {}".format(", ".join(flag_names)) + @flags.multi_flags_validator(["tpu"] + flag_names, message=msg) + def _path_check(flag_values): # pylint: disable=missing-docstring + if flag_values["tpu"] is None: + return True + + valid_flags = True + for key in flag_names: + if not flag_values[key].startswith("gs://"): + tf.compat.v1.logging.error("{} must be a GCS path.".format(key)) + valid_flags = False + + return valid_flags + + +def define_device(tpu=True): + """Register device specific flags. + Args: + tpu: Create flags to specify TPU operation. + Returns: + A list of flags for core.py to marks as key flags. + """ + + key_flags = [] + + if tpu: + flags.DEFINE_string( + name="tpu", default=None, + help=help_wrap( + "The Cloud TPU to use for training. This should be either the name " + "used when creating the Cloud TPU, or a " + "grpc://ip.address.of.tpu:8470 url. Passing `local` will use the" + "CPU of the local instance instead. (Good for debugging.)")) + key_flags.append("tpu") + + flags.DEFINE_string( + name="tpu_zone", default=None, + help=help_wrap( + "[Optional] GCE zone where the Cloud TPU is located in. If not " + "specified, we will attempt to automatically detect the GCE " + "project from metadata.")) + + flags.DEFINE_string( + name="tpu_gcp_project", default=None, + help=help_wrap( + "[Optional] Project name for the Cloud TPU-enabled project. If not " + "specified, we will attempt to automatically detect the GCE " + "project from metadata.")) + + flags.DEFINE_integer(name="num_tpu_shards", default=8, + help=help_wrap("Number of shards (TPU chips).")) + + return key_flags diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/core.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/core.py new file mode 100644 index 0000000000000000000000000000000000000000..35404f2c39f0a03a4095749af55cdd277cbfdfde --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/core.py @@ -0,0 +1,133 @@ +# Copyright 2018 The TensorFlow Authors. 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. +# ============================================================================== +"""Public interface for flag definition. + +See _example.py for detailed instructions on defining flags. +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import sys +from six.moves import shlex_quote + +from absl import app as absl_app +from absl import flags + +from TensorFlow.utils.flags import _base +from TensorFlow.utils.flags import _benchmark +from TensorFlow.utils.flags import _conventions +from TensorFlow.utils.flags import _device +from TensorFlow.utils.flags import _distribution +from TensorFlow.utils.flags import _misc +from TensorFlow.utils.flags import _performance + + +def set_defaults(**kwargs): + for key, value in kwargs.items(): + flags.FLAGS.set_default(name=key, value=value) + + +def parse_flags(argv=None): + """Reset flags and reparse. Currently only used in testing.""" + flags.FLAGS.unparse_flags() + absl_app.parse_flags_with_usage(argv or sys.argv) + + +def register_key_flags_in_core(f): + """Defines a function in core.py, and registers its key flags. + + absl uses the location of a flags.declare_key_flag() to determine the context + in which a flag is key. By making all declares in core, this allows model + main functions to call flags.adopt_module_key_flags() on core and correctly + chain key flags. + + Args: + f: The function to be wrapped + + Returns: + The "core-defined" version of the input function. + """ + + def core_fn(*args, **kwargs): + key_flags = f(*args, **kwargs) + [flags.declare_key_flag(fl) for fl in key_flags] # pylint: disable=expression-not-assigned + return core_fn + + +define_base = register_key_flags_in_core(_base.define_base) +# We have define_base_eager for compatibility, since it used to be a separate +# function from define_base. +define_base_eager = define_base +define_log_steps = register_key_flags_in_core(_benchmark.define_log_steps) +define_benchmark = register_key_flags_in_core(_benchmark.define_benchmark) +define_device = register_key_flags_in_core(_device.define_device) +define_image = register_key_flags_in_core(_misc.define_image) +define_performance = register_key_flags_in_core(_performance.define_performance) +define_distribution = register_key_flags_in_core( + _distribution.define_distribution) + + +help_wrap = _conventions.help_wrap + + +get_num_gpus = _base.get_num_gpus +get_tf_dtype = _performance.get_tf_dtype +get_loss_scale = _performance.get_loss_scale +DTYPE_MAP = _performance.DTYPE_MAP +require_cloud_storage = _device.require_cloud_storage + +def _get_nondefault_flags_as_dict(): + """Returns the nondefault flags as a dict from flag name to value.""" + nondefault_flags = {} + for flag_name in flags.FLAGS: + flag_value = getattr(flags.FLAGS, flag_name) + if (flag_name != flags.FLAGS[flag_name].short_name and + flag_value != flags.FLAGS[flag_name].default): + nondefault_flags[flag_name] = flag_value + return nondefault_flags + + +def get_nondefault_flags_as_str(): + """Returns flags as a string that can be passed as command line arguments. + + E.g., returns: "--batch_size=256 --use_synthetic_data" for the following code + block: + + ``` + flags.FLAGS.batch_size = 256 + flags.FLAGS.use_synthetic_data = True + print(get_nondefault_flags_as_str()) + ``` + + Only flags with nondefault values are returned, as passing default flags as + command line arguments has no effect. + + Returns: + A string with the flags, that can be passed as command line arguments to a + program to use the flags. + """ + nondefault_flags = _get_nondefault_flags_as_dict() + flag_strings = [] + for name, value in sorted(nondefault_flags.items()): + if isinstance(value, bool): + flag_str = '--{}'.format(name) if value else '--no{}'.format(name) + elif isinstance(value, list): + flag_str = '--{}={}'.format(name, ','.join(value)) + else: + flag_str = '--{}={}'.format(name, value) + flag_strings.append(flag_str) + return ' '.join(shlex_quote(flag_str) for flag_str in flag_strings) diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/guidelines.md b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..f168b67cfa0b4a11d414950d0279ec40127940e7 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/guidelines.md @@ -0,0 +1,65 @@ +# Using flags in official models + +1. **All common flags must be incorporated in the models.** + + Common flags (i.e. batch_size, model_dir, etc.) are provided by various flag definition functions, + and channeled through `official.utils.flags.core`. For instance to define common supervised + learning parameters one could use the following code: + + ```$xslt + from absl import app as absl_app + from absl import flags + + from TensorFlow.utils.flags import core as flags_core + + + def define_flags(): + flags_core.define_base() + flags.adopt_key_flags(flags_core) + + + def main(_): + flags_obj = flags.FLAGS + print(flags_obj) + + + if __name__ == "__main__" + absl_app.run(main) + ``` +2. **Validate flag values.** + + See the [Validators](#validators) section for implementation details. + + Validators in the official model repo should not access the file system, such as verifying + that files exist, due to the strict ordering requirements. + +3. **Flag values should not be mutated.** + + Instead of mutating flag values, use getter functions to return the desired values. An example + getter function is `get_tf_dtype` function below: + + ``` + # Map string to TensorFlow dtype + DTYPE_MAP = { + "fp16": tf.float16, + "fp32": tf.float32, + } + + def get_tf_dtype(flags_obj): + if getattr(flags_obj, "fp16_implementation", None) == "graph_rewrite": + # If the graph_rewrite is used, we build the graph with fp32, and let the + # graph rewrite change ops to fp16. + return tf.float32 + return DTYPE_MAP[flags_obj.dtype] + + + def main(_): + flags_obj = flags.FLAGS() + + # Do not mutate flags_obj + # if flags_obj.fp16_implementation == "graph_rewrite": + # flags_obj.dtype = "float32" # Don't do this + + print(get_tf_dtype(flags_obj)) + ... + ``` \ No newline at end of file diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/misc/callstack_sampler.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/misc/callstack_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..984f133e9c68a73569717bff47154110c718e3ce --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/misc/callstack_sampler.py @@ -0,0 +1,62 @@ +"""A simple Python callstack sampler.""" + +import contextlib +import datetime +import signal +import traceback + + +class CallstackSampler(object): + """A simple signal-based Python callstack sampler. + """ + + def __init__(self, interval=None): + self.stacks = [] + self.interval = 0.001 if interval is None else interval + + def _sample(self, signum, frame): + """Samples the current stack.""" + del signum + stack = traceback.extract_stack(frame) + formatted_stack = [] + formatted_stack.append(datetime.datetime.utcnow()) + for filename, lineno, function_name, text in stack: + formatted_frame = '{}:{}({})({})'.format(filename, lineno, function_name, + text) + formatted_stack.append(formatted_frame) + self.stacks.append(formatted_stack) + signal.setitimer(signal.ITIMER_VIRTUAL, self.interval, 0) + + @contextlib.contextmanager + def profile(self): + signal.signal(signal.SIGVTALRM, self._sample) + signal.setitimer(signal.ITIMER_VIRTUAL, self.interval, 0) + try: + yield + finally: + signal.setitimer(signal.ITIMER_VIRTUAL, 0) + + def save(self, fname): + with open(fname, 'w') as f: + for s in self.stacks: + for l in s: + f.write('%s\n' % l) + f.write('\n') + + +@contextlib.contextmanager +def callstack_sampling(filename, interval=None): + """Periodically samples the Python callstack. + + Args: + filename: the filename + interval: the sampling interval, in seconds. Defaults to 0.001. + + Yields: + nothing + """ + sampler = CallstackSampler(interval=interval) + with sampler.profile(): + yield + sampler.save(filename) + diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/testing/__init__.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/testing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/testing/benchmark_wrappers.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/testing/benchmark_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..a1c5327834ca2e04dfb6cdef17edc438da5f03c2 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/testing/benchmark_wrappers.py @@ -0,0 +1,83 @@ +# Lint as: python3 +"""Utils to annotate and trace benchmarks.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from absl import flags +from absl import logging +from absl.testing import flagsaver + +FLAGS = flags.FLAGS + +flags.DEFINE_multi_string( + 'benchmark_method_flags', None, + 'Optional list of runtime flags of the form key=value. Specify ' + 'multiple times to specify different flags. These will override the FLAGS ' + 'object directly after hardcoded settings in individual benchmark methods ' + 'before they call _run_and_report benchmark. Example if we set ' + '--benchmark_method_flags=train_steps=10 and a benchmark method hardcodes ' + 'FLAGS.train_steps=10000 and later calls _run_and_report_benchmark, ' + 'it\'ll only run for 10 steps. This is useful for ' + 'debugging/profiling workflows.') + + +def enable_runtime_flags(decorated_func): + """Sets attributes from --benchmark_method_flags for method execution. + + @enable_runtime_flags decorator temporarily adds flags passed in via + --benchmark_method_flags and runs the decorated function in that context. + + A user can set --benchmark_method_flags=train_steps=5 to run the benchmark + method in the snippet below with FLAGS.train_steps=5 for debugging (without + modifying the benchmark code). + + class ModelBenchmark(): + + @benchmark_wrappers.enable_runtime_flags + def _run_and_report_benchmark(self): + # run benchmark ... + # report benchmark results ... + + def benchmark_method(self): + FLAGS.train_steps = 1000 + ... + self._run_and_report_benchmark() + + Args: + decorated_func: The method that runs the benchmark after previous setup + execution that set some flags. + + Returns: + new_func: The same method which executes in a temporary context where flag + overrides from --benchmark_method_flags are active. + """ + + def runner(*args, **kwargs): + """Creates a temporary context to activate --benchmark_method_flags.""" + if FLAGS.benchmark_method_flags: + saved_flag_values = flagsaver.save_flag_values() + for key_value in FLAGS.benchmark_method_flags: + key, value = key_value.split('=', 1) + try: + numeric_float = float(value) + numeric_int = int(numeric_float) + if abs(numeric_int) == abs(numeric_float): + flag_value = numeric_int + else: + flag_value = numeric_float + except ValueError: + flag_value = value + logging.info('Setting --%s=%s', key, flag_value) + setattr(FLAGS, key, flag_value) + else: + saved_flag_values = None + try: + result = decorated_func(*args, **kwargs) + return result + finally: + if saved_flag_values: + flagsaver.restore_flag_values(saved_flag_values) + + return runner diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/LICENSE b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ac6cc52200857b96456cb1ab284bfec779b8947c --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/LICENSE @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2021 Habana Labs, Ltd. an Intel Company +Copyright (c) Soumith Chintala 2016, +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/mlperf_variable_map.json b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/mlperf_variable_map.json new file mode 100644 index 0000000000000000000000000000000000000000..7f9829d610990716d4cc956131eb90f7347bf025 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/mlperf_variable_map.json @@ -0,0 +1,163 @@ +{ + "conv1.weight": "conv0_weight", + "bn1.weight": "bn0_gamma", + "bn1.bias": "bn0_beta", + "layer1.0.conv1.weight": "stage1_unit1_conv1_weight", + "layer1.0.bn1.weight": "stage1_unit1_bn1_gamma", + "layer1.0.bn1.bias": "stage1_unit1_bn1_beta", + "layer1.0.conv2.weight": "stage1_unit1_conv2_weight", + "layer1.0.bn2.weight": "stage1_unit1_bn2_gamma", + "layer1.0.bn2.bias": "stage1_unit1_bn2_beta", + "layer1.0.conv3.weight": "stage1_unit1_conv3_weight", + "layer1.0.bn3.weight": "stage1_unit1_bn3_gamma", + "layer1.0.bn3.bias": "stage1_unit1_bn3_beta", + "layer1.0.downsample.0.weight": "stage1_unit1_conv1sc_weight", + "layer1.0.downsample.1.weight": "stage1_unit1_bnsc_gamma", + "layer1.0.downsample.1.bias": "stage1_unit1_bnsc_beta", + "layer1.1.conv1.weight": "stage1_unit2_conv1_weight", + "layer1.1.bn1.weight": "stage1_unit2_bn1_gamma", + "layer1.1.bn1.bias": "stage1_unit2_bn1_beta", + "layer1.1.conv2.weight": "stage1_unit2_conv2_weight", + "layer1.1.bn2.weight": "stage1_unit2_bn2_gamma", + "layer1.1.bn2.bias": "stage1_unit2_bn2_beta", + "layer1.1.conv3.weight": "stage1_unit2_conv3_weight", + "layer1.1.bn3.weight": "stage1_unit2_bn3_gamma", + "layer1.1.bn3.bias": "stage1_unit2_bn3_beta", + "layer1.2.conv1.weight": "stage1_unit3_conv1_weight", + "layer1.2.bn1.weight": "stage1_unit3_bn1_gamma", + "layer1.2.bn1.bias": "stage1_unit3_bn1_beta", + "layer1.2.conv2.weight": "stage1_unit3_conv2_weight", + "layer1.2.bn2.weight": "stage1_unit3_bn2_gamma", + "layer1.2.bn2.bias": "stage1_unit3_bn2_beta", + "layer1.2.conv3.weight": "stage1_unit3_conv3_weight", + "layer1.2.bn3.weight": "stage1_unit3_bn3_gamma", + "layer1.2.bn3.bias": "stage1_unit3_bn3_beta", + "layer2.0.conv1.weight": "stage2_unit1_conv1_weight", + "layer2.0.bn1.weight": "stage2_unit1_bn1_gamma", + "layer2.0.bn1.bias": "stage2_unit1_bn1_beta", + "layer2.0.conv2.weight": "stage2_unit1_conv2_weight", + "layer2.0.bn2.weight": "stage2_unit1_bn2_gamma", + "layer2.0.bn2.bias": "stage2_unit1_bn2_beta", + "layer2.0.conv3.weight": "stage2_unit1_conv3_weight", + "layer2.0.bn3.weight": "stage2_unit1_bn3_gamma", + "layer2.0.bn3.bias": "stage2_unit1_bn3_beta", + "layer2.0.downsample.0.weight": "stage2_unit1_conv1sc_weight", + "layer2.0.downsample.1.weight": "stage2_unit1_bnsc_gamma", + "layer2.0.downsample.1.bias": "stage2_unit1_bnsc_beta", + "layer2.1.conv1.weight": "stage2_unit2_conv1_weight", + "layer2.1.bn1.weight": "stage2_unit2_bn1_gamma", + "layer2.1.bn1.bias": "stage2_unit2_bn1_beta", + "layer2.1.conv2.weight": "stage2_unit2_conv2_weight", + "layer2.1.bn2.weight": "stage2_unit2_bn2_gamma", + "layer2.1.bn2.bias": "stage2_unit2_bn2_beta", + "layer2.1.conv3.weight": "stage2_unit2_conv3_weight", + "layer2.1.bn3.weight": "stage2_unit2_bn3_gamma", + "layer2.1.bn3.bias": "stage2_unit2_bn3_beta", + "layer2.2.conv1.weight": "stage2_unit3_conv1_weight", + "layer2.2.bn1.weight": "stage2_unit3_bn1_gamma", + "layer2.2.bn1.bias": "stage2_unit3_bn1_beta", + "layer2.2.conv2.weight": "stage2_unit3_conv2_weight", + "layer2.2.bn2.weight": "stage2_unit3_bn2_gamma", + "layer2.2.bn2.bias": "stage2_unit3_bn2_beta", + "layer2.2.conv3.weight": "stage2_unit3_conv3_weight", + "layer2.2.bn3.weight": "stage2_unit3_bn3_gamma", + "layer2.2.bn3.bias": "stage2_unit3_bn3_beta", + "layer2.3.conv1.weight": "stage2_unit4_conv1_weight", + "layer2.3.bn1.weight": "stage2_unit4_bn1_gamma", + "layer2.3.bn1.bias": "stage2_unit4_bn1_beta", + "layer2.3.conv2.weight": "stage2_unit4_conv2_weight", + "layer2.3.bn2.weight": "stage2_unit4_bn2_gamma", + "layer2.3.bn2.bias": "stage2_unit4_bn2_beta", + "layer2.3.conv3.weight": "stage2_unit4_conv3_weight", + "layer2.3.bn3.weight": "stage2_unit4_bn3_gamma", + "layer2.3.bn3.bias": "stage2_unit4_bn3_beta", + "layer3.0.conv1.weight": "stage3_unit1_conv1_weight", + "layer3.0.bn1.weight": "stage3_unit1_bn1_gamma", + "layer3.0.bn1.bias": "stage3_unit1_bn1_beta", + "layer3.0.conv2.weight": "stage3_unit1_conv2_weight", + "layer3.0.bn2.weight": "stage3_unit1_bn2_gamma", + "layer3.0.bn2.bias": "stage3_unit1_bn2_beta", + "layer3.0.conv3.weight": "stage3_unit1_conv3_weight", + "layer3.0.bn3.weight": "stage3_unit1_bn3_gamma", + "layer3.0.bn3.bias": "stage3_unit1_bn3_beta", + "layer3.0.downsample.0.weight": "stage3_unit1_conv1sc_weight", + "layer3.0.downsample.1.weight": "stage3_unit1_bnsc_gamma", + "layer3.0.downsample.1.bias": "stage3_unit1_bnsc_beta", + "layer3.1.conv1.weight": "stage3_unit2_conv1_weight", + "layer3.1.bn1.weight": "stage3_unit2_bn1_gamma", + "layer3.1.bn1.bias": "stage3_unit2_bn1_beta", + "layer3.1.conv2.weight": "stage3_unit2_conv2_weight", + "layer3.1.bn2.weight": "stage3_unit2_bn2_gamma", + "layer3.1.bn2.bias": "stage3_unit2_bn2_beta", + "layer3.1.conv3.weight": "stage3_unit2_conv3_weight", + "layer3.1.bn3.weight": "stage3_unit2_bn3_gamma", + "layer3.1.bn3.bias": "stage3_unit2_bn3_beta", + "layer3.2.conv1.weight": "stage3_unit3_conv1_weight", + "layer3.2.bn1.weight": "stage3_unit3_bn1_gamma", + "layer3.2.bn1.bias": "stage3_unit3_bn1_beta", + "layer3.2.conv2.weight": "stage3_unit3_conv2_weight", + "layer3.2.bn2.weight": "stage3_unit3_bn2_gamma", + "layer3.2.bn2.bias": "stage3_unit3_bn2_beta", + "layer3.2.conv3.weight": "stage3_unit3_conv3_weight", + "layer3.2.bn3.weight": "stage3_unit3_bn3_gamma", + "layer3.2.bn3.bias": "stage3_unit3_bn3_beta", + "layer3.3.conv1.weight": "stage3_unit4_conv1_weight", + "layer3.3.bn1.weight": "stage3_unit4_bn1_gamma", + "layer3.3.bn1.bias": "stage3_unit4_bn1_beta", + "layer3.3.conv2.weight": "stage3_unit4_conv2_weight", + "layer3.3.bn2.weight": "stage3_unit4_bn2_gamma", + "layer3.3.bn2.bias": "stage3_unit4_bn2_beta", + "layer3.3.conv3.weight": "stage3_unit4_conv3_weight", + "layer3.3.bn3.weight": "stage3_unit4_bn3_gamma", + "layer3.3.bn3.bias": "stage3_unit4_bn3_beta", + "layer3.4.conv1.weight": "stage3_unit5_conv1_weight", + "layer3.4.bn1.weight": "stage3_unit5_bn1_gamma", + "layer3.4.bn1.bias": "stage3_unit5_bn1_beta", + "layer3.4.conv2.weight": "stage3_unit5_conv2_weight", + "layer3.4.bn2.weight": "stage3_unit5_bn2_gamma", + "layer3.4.bn2.bias": "stage3_unit5_bn2_beta", + "layer3.4.conv3.weight": "stage3_unit5_conv3_weight", + "layer3.4.bn3.weight": "stage3_unit5_bn3_gamma", + "layer3.4.bn3.bias": "stage3_unit5_bn3_beta", + "layer3.5.conv1.weight": "stage3_unit6_conv1_weight", + "layer3.5.bn1.weight": "stage3_unit6_bn1_gamma", + "layer3.5.bn1.bias": "stage3_unit6_bn1_beta", + "layer3.5.conv2.weight": "stage3_unit6_conv2_weight", + "layer3.5.bn2.weight": "stage3_unit6_bn2_gamma", + "layer3.5.bn2.bias": "stage3_unit6_bn2_beta", + "layer3.5.conv3.weight": "stage3_unit6_conv3_weight", + "layer3.5.bn3.weight": "stage3_unit6_bn3_gamma", + "layer3.5.bn3.bias": "stage3_unit6_bn3_beta", + "layer4.0.conv1.weight": "stage4_unit1_conv1_weight", + "layer4.0.bn1.weight": "stage4_unit1_bn1_gamma", + "layer4.0.bn1.bias": "stage4_unit1_bn1_beta", + "layer4.0.conv2.weight": "stage4_unit1_conv2_weight", + "layer4.0.bn2.weight": "stage4_unit1_bn2_gamma", + "layer4.0.bn2.bias": "stage4_unit1_bn2_beta", + "layer4.0.conv3.weight": "stage4_unit1_conv3_weight", + "layer4.0.bn3.weight": "stage4_unit1_bn3_gamma", + "layer4.0.bn3.bias": "stage4_unit1_bn3_beta", + "layer4.0.downsample.0.weight": "stage4_unit1_conv1sc_weight", + "layer4.0.downsample.1.weight": "stage4_unit1_bnsc_gamma", + "layer4.0.downsample.1.bias": "stage4_unit1_bnsc_beta", + "layer4.1.conv1.weight": "stage4_unit2_conv1_weight", + "layer4.1.bn1.weight": "stage4_unit2_bn1_gamma", + "layer4.1.bn1.bias": "stage4_unit2_bn1_beta", + "layer4.1.conv2.weight": "stage4_unit2_conv2_weight", + "layer4.1.bn2.weight": "stage4_unit2_bn2_gamma", + "layer4.1.bn2.bias": "stage4_unit2_bn2_beta", + "layer4.1.conv3.weight": "stage4_unit2_conv3_weight", + "layer4.1.bn3.weight": "stage4_unit2_bn3_gamma", + "layer4.1.bn3.bias": "stage4_unit2_bn3_beta", + "layer4.2.conv1.weight": "stage4_unit3_conv1_weight", + "layer4.2.bn1.weight": "stage4_unit3_bn1_gamma", + "layer4.2.bn1.bias": "stage4_unit3_bn1_beta", + "layer4.2.conv2.weight": "stage4_unit3_conv2_weight", + "layer4.2.bn2.weight": "stage4_unit3_bn2_gamma", + "layer4.2.bn2.bias": "stage4_unit3_bn2_beta", + "layer4.2.conv3.weight": "stage4_unit3_conv3_weight", + "layer4.2.bn3.weight": "stage4_unit3_bn3_gamma", + "layer4.2.bn3.bias": "stage4_unit3_bn3_beta", + "fc.weight": "fc1_weight", + "fc.bias": "fc1_bias" +} \ No newline at end of file diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/model/__init__.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b792ca6ecf7cbe1d51c5c1dd72f1f98328fda8b9 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/model/__init__.py @@ -0,0 +1 @@ +from .resnet import * diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/model/optimizer.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/model/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..1aeef4f1c624bb02ab0e1509baf578a34e707689 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/model/optimizer.py @@ -0,0 +1,59 @@ +# Copyright (C) 2022 Habana Labs, Ltd. an Intel Company + +import torch +from torch.optim.lr_scheduler import _LRScheduler + +class PolynomialDecayWithWarmup(_LRScheduler): + """Polynomial learning rate decay until step reach to max_decay_step + + Args + optimizer (Optimizer): Wrapped optimizer. + max_decay_steps: after this step, we stop decreasing learning rate + end_learning_rate: scheduler stoping learning rate decay, value of learning rate must be this value + power: The power of the polynomial. + """ + + def __init__(self, optimizer, batch_size, steps_per_epoch, train_steps, initial_learning_rate=9.0, warmup_epochs=3, + end_learning_rate=0.0001, power=2.0, lars_decay_epochs=36, mlperf_mlloger=None, mlperf_mllog=None, opt_name=None): + self.last_step = 0 + self.steps_per_epoch = steps_per_epoch + self.train_steps = train_steps + self.initial_learning_rate = initial_learning_rate + self.warmup_epochs = warmup_epochs + self.end_learning_rate = end_learning_rate + self.power = power + self.warmup_steps = warmup_epochs * (steps_per_epoch - 1) + self.decay_steps = lars_decay_epochs * (steps_per_epoch - 1) - self.warmup_steps + 1 + self.opt_name = opt_name.lower() + + mlperf_mlloger.event(key=mlperf_mllog.constants.LARS_OPT_END_LR, value=self.end_learning_rate) + mlperf_mlloger.event(key=mlperf_mllog.constants.LARS_OPT_LR_DECAY_STEPS, value=int(self.decay_steps)) + mlperf_mlloger.event(key=mlperf_mllog.constants.LARS_OPT_LR_DECAY_POLY_POWER, value=power) + mlperf_mlloger.event(key=self.opt_name+'_'+mlperf_mllog.constants.OPT_LR_WARMUP_EPOCHS, value=float(self.warmup_epochs)) + mlperf_mlloger.event(key=self.opt_name+'_'+mlperf_mllog.constants.OPT_BASE_LR, value=self.initial_learning_rate) + + super().__init__(optimizer) + + def get_lr(self): + warmup_steps = self.warmup_steps + warmup_rate = ( + self.initial_learning_rate * self.last_step / warmup_steps) + + poly_steps = self.last_step - warmup_steps + poly_steps = poly_steps if poly_steps > 1 else 1 + + poly_rate = (self.initial_learning_rate - self.end_learning_rate) * \ + ((1 - poly_steps / self.decay_steps) ** + (self.power)) + self.end_learning_rate + + decay_rate = warmup_rate if self.last_step <= warmup_steps else poly_rate + return decay_rate + + def step(self, step=None): + if step is None: + step = self.last_step + 1 + self.last_step = step if step != 0 else 1 + if self.last_step <= self.decay_steps + self.warmup_steps: + decay_lrs = [self.get_lr()] + for param_group, lr in zip(self.optimizer.param_groups, decay_lrs): + param_group['lr'] = lr diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/ops_fp32_Resnet.txt b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/ops_fp32_Resnet.txt new file mode 100644 index 0000000000000000000000000000000000000000..2c7f49cdf48e39263361cfcbddb9b0caafa46398 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/ops_fp32_Resnet.txt @@ -0,0 +1,5 @@ +cross_entropy_loss +log_softmax +nll_loss +softmax +topk diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/requirements.txt b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..e1a441a144f53588e5f362b519279df7f3370990 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/requirements.txt @@ -0,0 +1,4 @@ +mpi4py>=3.0.3 +scipy>=1.7.1 +colorlog==6.6.0 +git+https://github.com/mlperf/logging.git@1.0.0 diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/debug.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/debug.py new file mode 100644 index 0000000000000000000000000000000000000000..66f44596be9f24aab7e7ccf61ea7a3c7d7a54631 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/debug.py @@ -0,0 +1,107 @@ +# Copyright 2019 The TensorFlow Authors. 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 (C) 2020-2021 Habana Labs, Ltd. an Intel Company +############################################################################### + +from absl import flags +from absl import logging +from tensorflow.core.protobuf import debug_event_pb2 +from tensorflow.python.debug.lib import debug_events_writer +from tensorflow.python.framework import op_callbacks +from tensorflow.python.ops import gen_debug_ops +import tensorflow as tf +import re +import json + +flags.DEFINE_string(name='dump_config', default=None, help='Defines config for tensor dumping') + + +class _DumpCallback(object): + def __init__(self, dump_root, tensor_debug_mode, circular_buffer_size, op_regex): + self._dump_root = dump_root + self._tensor_debug_mode = debug_event_pb2.TensorDebugMode.Value(tensor_debug_mode) + self._circular_buffer_size = circular_buffer_size + self._op_regex = re.compile(op_regex) if isinstance(op_regex, str) else op_regex + self._tfdbg_run_id = '' + self._dump_op_counter = 0 + + debug_writer_args = { + "dump_root" : self._dump_root, + "circular_buffer_size": self._circular_buffer_size + } + + if tf.__version__.startswith("2.4"): + debug_writer_args["tfdbg_run_id"] = self._tfdbg_run_id + + self._writer = debug_events_writer.DebugEventsWriter(**debug_writer_args) + + def callback(self, op_type, inputs, attrs, outputs, op_name=None, graph=None): + if op_name is not None and self._op_regex.match(op_name): + graph_name = "missing-graph-name" + if graph is not None and hasattr(graph, "name"): + graph_name=graph.name + + logging.info("Adding dump op for '%s' of type '%s' from graph '%s'" %(op_name, op_type, graph_name)) + + new_outputs = [] + + for output_slot, output in enumerate(outputs): + debug_identity_op_kwargs = { + "tfdbg_context_id": graph_name, + "op_name": op_name, + "output_slot": output_slot, + "tensor_debug_mode": self._tensor_debug_mode, + "debug_urls": ["file://%s" % self._dump_root], + "name": "dump_%d" % self._dump_op_counter + } + + if tf.__version__.startswith("2.4"): + debug_identity_op_kwargs["circular_buffer_size"] = self._circular_buffer_size + debug_identity_op_kwargs["tfdbg_run_id"] = self._tfdbg_run_id + + self._dump_op_counter = self._dump_op_counter + 1 + new_outputs.append(gen_debug_ops.debug_identity_v2(output, **debug_identity_op_kwargs)) + + return new_outputs + else: + return None + + def __enter__(self, *args, **kwargs): + op_callbacks.add_op_callback(self.callback) + logging.info("Enabled tensor dumping") + + def __exit__(self, *args, **kwargs): + op_callbacks.remove_op_callback(self.callback) + logging.info("Disabled tensor dumping") + + def __del__(self): + self._writer.Close() + +class _Dummy(object): + def __enter__(self, *args, **kwargs): + pass + def __exit__(self, *args, **kwargs): + pass + +def dump_callback(config_file=None): + if config_file is not None: + kwargs = json.load(open(config_file, 'r')) + return _DumpCallback(**kwargs) + try: + kwargs = json.load(open(flags.FLAGS.dump_config, 'r')) + return _DumpCallback(**kwargs) + except: + return _Dummy() diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/modeling/__init__.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/modeling/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/modeling/performance.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/modeling/performance.py new file mode 100644 index 0000000000000000000000000000000000000000..09f9161044aa2c251ccbfd155c81469e9a3bddc0 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/modeling/performance.py @@ -0,0 +1,56 @@ +# Lint as: python3 +# Copyright 2020 The TensorFlow Authors. 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. +# ============================================================================== +"""Functions and classes related to training performance.""" + +import tensorflow as tf + + +def configure_optimizer(optimizer, + use_float16=False, + use_graph_rewrite=False, + loss_scale="dynamic"): + """Configures optimizer object with performance options.""" + if use_float16: + # Wraps optimizer with a LossScaleOptimizer. This is done automatically + # in compile() with the "mixed_float16" policy, but since we do not call + # compile(), we must wrap the optimizer manually. + optimizer = ( + tf.keras.mixed_precision.LossScaleOptimizer( + optimizer, loss_scale=loss_scale)) + if use_graph_rewrite: + # Note: the model dtype must be 'float32', which will ensure + # tf.ckeras.mixed_precision and + # tf.compat.v1.mixed_precision.enable_mixed_precision_graph_rewrite do not double + # up. + optimizer = tf.compat.v1.mixed_precision.enable_mixed_precision_graph_rewrite( + optimizer) + return optimizer + + +def set_mixed_precision_policy(dtype, loss_scale=None): + """Sets mix precision policy.""" + if dtype == tf.float16: + policy = tf.keras.mixed_precision.Policy( + 'mixed_float16', loss_scale=loss_scale) + tf.keras.mixed_precision.set_global_policy(policy) + elif dtype == tf.bfloat16: + policy = tf.keras.mixed_precision.Policy( + 'mixed_bfloat16') + tf.keras.mixed_precision.set_global_policy(policy) + elif dtype == tf.float32: + tf.keras.mixed_precision.set_global_policy('float32') + else: + raise ValueError("Unexpected dtype: %s" % dtype) diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/tb_utils.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/tb_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ea28099bd5a9b6e0df0faa00e2611d108167e620 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/tb_utils.py @@ -0,0 +1,357 @@ +import os +import time +import tensorflow as tf +from copy import deepcopy +from tensorboard.plugins.hparams import api as hp +from tensorflow.python.eager import context +from tensorflow.keras import backend as K +from tensorflow.python.ops import summary_ops_v2 +from tensorflow.python.summary import summary as tf_summary +from tensorflow.python.training.summary_io import SummaryWriterCache +from tensorflow.compat.v1.keras.callbacks import TensorBoard, Callback + + +def _remove_prefix(s, prefix): + if s.startswith(prefix): + s = s[len(prefix):] + return s + + +def _parse_precision(): + flag = os.environ.get('TF_BF16_CONVERSION', '0') + flag = flag.lower() + try: + value = int(flag) + except: + value = -1 + + if flag == 'false' or value == 0: + return 'fp32' + elif flag == 'true' or value == 1: + return 'bf16' + return flag + + +def _set_precision_if_missing(hparams: dict): + if 'precision' not in hparams: + hparams['precision'] = _parse_precision() + return hparams + + +def _copy_and_clean_hparams(hparams: dict): + hparams_ = dict() + for name, value in hparams.items(): + if isinstance(value, (str, bool, int, float)): + hparams_[name] = value + continue + + try: + hparams_[name] = str(value) + tf.compat.v1.logging.info( + f'Type of parameter "{name}" is not one of (bool, int, float, str). ' + 'It will be saved as a string.') + except: + tf.compat.v1.logging.info( + f'Conversion of parameter "{name}" to string failed. ' + 'Parameter will not be saved.') + + return hparams_ + + +def write_hparams_v1(writer, hparams: dict): + hparams = _copy_and_clean_hparams(hparams) + hparams = _set_precision_if_missing(hparams) + + with tf.compat.v1.Graph().as_default(): + if isinstance(writer, str): + writer = SummaryWriterCache.get(writer) + summary = hp.hparams_pb(hparams).SerializeToString() + writer.add_summary(summary) + + +def write_hparams_v2(writer, hparams: dict): + hparams = _copy_and_clean_hparams(hparams) + hparams = _set_precision_if_missing(hparams) + + with writer.as_default(): + hp.hparams(hparams) + + +class ExamplesPerSecondEstimatorHook(tf.compat.v1.train.StepCounterHook): + """Calculate and report global_step/sec and examples/sec during runtime.""" + # Copy-pasted from tensorflow_estimator/python/estimator/tpu/tpu_estimator.py + + def __init__(self, + batch_size=None, + every_n_steps=1, + every_n_secs=None, + output_dir=None, + summary_writer=None, + extra_metrics=None, + log_global_step=False, + verbose=False): + super().__init__( + every_n_steps=every_n_steps, + every_n_secs=every_n_secs, + output_dir=output_dir, + summary_writer=summary_writer) + self._metrics = extra_metrics or {} + self._verbose = verbose + if log_global_step: + # Because estimator will log global_step/sec by default + # when log_step_count_steps is not None saving it here + # would duplicate events in TensorBoard. + # Use log_global_step=True when RunConfig.log_step_count_step=None + self._metrics['global_step/sec'] = 1 + if batch_size is not None: + self._metrics['examples/sec'] = batch_size + + def _add_summary(self, tag, value, step): + Summary = tf.compat.v1.Summary + global_step_summary = Summary(value=[ + Summary.Value(tag=tag, simple_value=value) + ]) + self._summary_writer.add_summary(global_step_summary, step) + if self._verbose: + tf.compat.v1.logging.info(f'{tag}: {value}') + + def _log_and_record(self, elapsed_steps, elapsed_time, global_step): + global_step_per_sec = elapsed_steps / elapsed_time + if self._summary_writer is not None: + for name, factor in self._metrics.items(): + value = factor * global_step_per_sec + self._add_summary(name, value, global_step) + + def after_create_session(self, session, coord): + self._timer.reset() + + +class ExamplesPerSecondKerasHookV1(Callback): + def __init__(self, + every_n_steps=1, + every_n_secs=None, + output_dir=None, + summary_writer=None, + batch_size=None): + self.writer = summary_writer or SummaryWriterCache.get(output_dir) + self._timer = tf.compat.v1.train.SecondOrStepTimer( + every_n_secs, every_n_steps) + self._total_examples = 0 + self._should_trigger = True + self._batch_size = batch_size + + def on_train_begin(self, logs=None): + self._timer.reset() + + def on_train_batch_begin(self, batch, logs=None): + self._should_trigger = self._timer.should_trigger_for_step( + logs.get('batch', batch)) + + def on_train_batch_end(self, batch, logs=None): + step = logs.get('batch', batch) + self._total_examples += logs.get('size', 0) + if self._should_trigger: + elapsed_time, elapsed_steps = self._timer.update_last_triggered_step( + step) + if elapsed_time is not None: + total_examples = self._total_examples + if self._batch_size is not None: + total_examples = self._batch_size * elapsed_steps + self._log_and_record( + elapsed_steps, elapsed_time, step, total_examples) + self._total_examples = 0 + + def _log_and_record(self, elapsed_steps, elapsed_time, + global_step, total_examples=None): + Summary = tf.compat.v1.Summary + global_step_per_sec = elapsed_steps / elapsed_time + if self.writer is not None: + global_step_summary = Summary(value=[ + Summary.Value( + tag='global_step/sec', simple_value=global_step_per_sec) + ]) + self.writer.add_summary(global_step_summary, global_step) + if total_examples is not None: + examples_per_sec = total_examples / elapsed_time + example_summary = Summary(value=[ + Summary.Value(tag='examples/sec', + simple_value=examples_per_sec) + ]) + self.writer.add_summary(example_summary, global_step) + + +class ExamplesPerSecondKerasHookV2(ExamplesPerSecondKerasHookV1): + def __init__(self, + every_n_steps=1, + every_n_secs=None, + output_dir=None, + summary_writer=None, + batch_size=None): + writer = summary_writer or summary_ops_v2.create_file_writer_v2(output_dir) + super().__init__(every_n_steps, every_n_secs, output_dir, writer, batch_size) + + def _log_and_record(self, elapsed_steps, elapsed_time, + global_step, total_examples=None): + global_step_per_sec = elapsed_steps / elapsed_time + if self.writer is not None: + with self.writer.as_default(), summary_ops_v2.always_record_summaries(): + summary_ops_v2.scalar('global_step/sec', global_step_per_sec, + step=global_step) + if total_examples is not None: + examples_per_sec = total_examples / elapsed_time + summary_ops_v2.scalar('examples/sec', examples_per_sec, + step=global_step) + + +ExamplesPerSecondKerasHook = ExamplesPerSecondKerasHookV1 + + +class TBSummary(object): + """ + Creates a proxy for FileWriter for TensorBoard. + + :param log_dir: - path where experiment is running (usually the same as + model_dir in Estimator) + """ + + def __init__(self, log_dir: str): + super().__init__() + self._log_dir = log_dir + self._session = None + + def __enter__(self): + self._session = tf.compat.v1.Session() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._session: + self._session.close() + self._session = None + + def add_scalar(self, tag, value, global_step=None): + with self._session: + writer = SummaryWriterCache.get(self._log_dir) + summary = tf.compat.v1.Summary( + value=[tf.compat.v1.Summary.Value(tag=tag, simple_value=value)]) + event = tf.compat.v1.Event(summary=summary) + event.wall_time = time.time() + event.step = global_step + writer.add_event(event) + + +class TensorBoardWithHParamsV1(TensorBoard): + """ + Adds TensorBoard visualization to training process. + + Writes training tfevent file into default log directory, but + stores evaluation in log_dir/eval subdirectory. + """ + + def __init__(self, hparams, *args, **kwargs): + super().__init__(*args, **kwargs) + self.hparams = hparams + self._train_summary = None + self._eval_summary = None + + def _switch_writer(self, mode): + self.writer = self._train_summary if mode == 'train' else self._eval_summary + + def _init_writer(self, model): + """Sets file writer.""" + if context.executing_eagerly(): + raise NotImplementedError('hook does not support eager execution') + + self._train_summary = SummaryWriterCache.get(self.log_dir) + self._eval_summary = SummaryWriterCache.get( + os.path.join(self.log_dir, 'eval')) + self._switch_writer('train') + + write_hparams_v1(self.writer, self.hparams) + + def _write_custom_summaries(self, step, logs=None): + """ + This methods works on the assumption that metrics containing `val` + in name are related to validation (that's the default in Keras). + """ + + logs = logs or {} + train_logs = {} + eval_logs = {} + + for name, value in logs.items(): + if 'val' in name: + if name.startswith('batch_val_'): + name = 'batch_' + _remove_prefix(name, 'batch_val_') + elif name.startswith('epoch_val_'): + name = _remove_prefix(name, 'epoch_val_') + eval_logs[name] = value + else: + if name.startswith('batch_'): + name = _remove_prefix(name, 'batch_') + train_logs[name] = value + + self._switch_writer('eval') + super()._write_custom_summaries(step, eval_logs) + self._switch_writer('train') + super()._write_custom_summaries(step, train_logs) + + +class TensorBoardWithHParamsV2(TensorBoard): + """ + Adds TensorBoard visualization to training process. + + Writes training tfevent file into default log directory, but + stores evaluation in log_dir/eval subdirectory. + """ + + def __init__(self, hparams, *args, **kwargs): + super().__init__(*args, **kwargs) + self.hparams = hparams + + def set_model(self, model): + """Sets Keras model and writes graph if specified.""" + self.model = model + self._log_write_dir = self._get_log_write_dir() + + self._train_dir = self._log_write_dir + self._train_step = self.model._train_counter # pylint: disable=protected-access + + self._val_dir = os.path.join(self._log_write_dir, 'eval') + self._val_step = self.model._test_counter # pylint: disable=protected-access + + self._writers = {} # Resets writers. + + self._should_write_train_graph = False + if self.write_graph: + self._write_keras_model_summary() + self._should_write_train_graph = True + if self.embeddings_freq: + self._configure_embeddings() + + write_hparams_v2(self._train_writer, self.hparams) + + def _log_epoch_metrics(self, epoch, logs): + """Writes epoch metrics out as scalar summaries. + + Arguments: + epoch: Int. The global step to use for TensorBoard. + logs: Dict. Keys are scalar summary names, values are scalars. + """ + if not logs: + return + + train_logs = {k: v for k, + v in logs.items() if not k.startswith('val_')} + val_logs = {k: v for k, v in logs.items() if k.startswith('val_')} + train_logs = self._collect_learning_rate(train_logs) + + with summary_ops_v2.always_record_summaries(): + if train_logs: + with self._train_writer.as_default(): + for name, value in train_logs.items(): + summary_ops_v2.scalar(name, value, step=epoch) + if val_logs: + with self._val_writer.as_default(): + for name, value in val_logs.items(): + name = name[4:] # Remove 'val_' prefix. + summary_ops_v2.scalar(name, value, step=epoch) diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/__init__.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..931c2ef11db4a949e6c2e95bca44e36bac1241e9 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/__init__.py @@ -0,0 +1,14 @@ +# Copyright 2019 The TensorFlow Authors. 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. +# ============================================================================== diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/controller.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..0248135b3747e2db6bd954db114e4c3d426aa76e --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/controller.py @@ -0,0 +1,395 @@ +# Copyright 2019 The TensorFlow Authors. 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. +# ============================================================================== +"""A light weight utilities to train TF2 models.""" + +from __future__ import absolute_import +from __future__ import division +# from __future__ import google_type_annotations +from __future__ import print_function + +import time +import os + +from absl import logging + +import tensorflow.compat.v2 as tf +from typing import Callable, Dict, Optional, Text + +from TensorFlow.common.training import utils + + +class Controller(object): + """Class that facilitates training and evaluation of models.""" + + def __init__( + self, + strategy: Optional[tf.distribute.Strategy] = None, + train_fn: Optional[Callable[[tf.Tensor], + Optional[Dict[Text, tf.Tensor]]]] = None, + eval_fn: Optional[Callable[[tf.Tensor], + Optional[Dict[Text, tf.Tensor]]]] = None, + warmup_fn: Optional[Callable[[tf.Tensor], + Optional[Dict[Text, tf.Tensor]]]] = None, + global_step: Optional[tf.Variable] = None, + # Train related + train_steps: Optional[int] = None, + steps_per_loop: Optional[int] = None, + summary_dir: Optional[Text] = None, + checkpoint_manager: Optional[tf.train.CheckpointManager] = None, + # summary related + summary_interval: Optional[int] = None, + # Evaluation related + eval_summary_dir: Optional[Text] = None, + eval_steps: Optional[int] = None, + eval_interval: Optional[int] = None, + eval_offset: Optional[int] = 0, + # Warmup related + device_warmup_steps: Optional[int] = None, + train_summary_writer: Optional[tf.summary.SummaryWriter] = None, + eval_summary_writer: Optional[tf.summary.SummaryWriter] = None): + """Constructs a `Controller` instance. + + Args: + strategy: An instance of `tf.distribute.Strategy`. + train_fn: A callable defined as `def train_fn(num_steps)`, which + `num_steps` indicates the number of steps to run for each loop. + eval_fn: A callable defined as `def eval_fn(num_steps)`, which `num_steps` + indicates the number of steps for one evaluation. + global_step: An integer `tf.Variable` indicating the global training step + number. Usually this can be obtained from `iterations` property of the + model's optimizer (e.g. `self.optimizer.iterations`), or users can + create their own global step variable as well. If the users create their + own global step variable, it is recommended to create the `tf.Variable` + inside strategy scope, and with + `aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA`. + train_steps: The total (maximum) number of training steps to perform. + steps_per_loop: The number of steps to run in each "inner loop" of + training (passed to the `num_steps` parameter of `train_fn`). + summary_dir: The directory to restore and write checkpoints and summaries. + If None, it will be set to `checkpoint_manager.directory`. + checkpoint_manager: An instance of `tf.train.CheckpointManager`. + summary_interval: Step interval for training summaries. Note that this + argument only applies to the summaries outside the training loop. If the + value is None, then training summaries are not enabled. + eval_summary_dir: The directory to write eval summaries. If None, it will + be set to `summary_dir`. + eval_steps: Number of steps to run evaluation. + eval_interval: Step interval for evaluation. If None, will skip evaluation + in the middle of training. Note that evaluation only happens outside the + training loop, which the loop iteration is specify by `steps_per_loop` + parameter. + eval_offset: Step number of the first evaluation. + train_summary_writer: Instance of tf.summary.SummaryWriter that should be + used for saving training summaries to TensorBoard. + eval_summary_writer: Instance of tf.summary.SummaryWriter that should be + used for saving evaluation summaries to TensorBoard. + + Raises: + ValueError: If both `train_fn` and `eval_fn` are None. + ValueError: If `train_fn` is not None and `train_steps` is None. + ValueError: If `steps_per_loop` is None when `train_fn` is provided. + ValueError: If `steps_per_loop` is not a positive integer. + """ + if train_fn is None and eval_fn is None: + raise ValueError("`train_fn` and `eval_fn` should not both be None") + + # TODO(rxsang): Support training until exhaustion by passing + # `train_steps=-1`. Currently it cannot be supported with a host training + # loop because break statements are not supported with distributed dataset. + if train_fn is not None: + if train_steps is None: + raise ValueError("`train_steps` is required when `train_fn` is " + "provided.") + if steps_per_loop is None: + raise ValueError("`steps_per_loop` is required when `train_fn is " + "provided.") + if not isinstance(steps_per_loop, int) or steps_per_loop < 1: + raise ValueError("`steps_per_loop` should be a positive integer") + if summary_interval is not None and summary_interval <= 0: + raise ValueError("`summary_interval` should be larger than 0") + + self.strategy = strategy or tf.distribute.get_strategy() + + self.train_fn = train_fn + self.eval_fn = eval_fn + self.warmup_fn = warmup_fn + self.global_step = global_step + self.checkpoint_manager = checkpoint_manager + self.last_eval_output = None + + if self.train_fn is not None: + self.train_steps = train_steps + self.steps_per_loop = steps_per_loop + self.summary_dir = summary_dir or checkpoint_manager.directory + + self.summary_interval = summary_interval + if train_summary_writer is not None: + summary_writer = train_summary_writer + summary_writer = tf.summary.create_file_writer( + self.summary_dir) if self.summary_interval else None + # TODO(rxsang): Consider pass SummaryManager directly into Controller for + # maximum customizability. + self.summary_manager = utils.SummaryManager( + summary_writer, + tf.summary.scalar, + global_step=self.global_step, + summary_interval=self.summary_interval) + + if self.eval_fn is not None: + if eval_summary_dir is None and self.summary_dir is not None: + eval_summary_dir = os.path.join(self.summary_dir, 'eval') + if eval_summary_writer is not None: + summary_writer = eval_summary_writer + elif eval_summary_dir: + summary_writer = tf.summary.create_file_writer(eval_summary_dir) + else: + summary_writer = None + self.eval_summary_manager = utils.SummaryManager( + summary_writer, tf.summary.scalar, global_step=self.global_step) + + self.eval_steps = eval_steps + self.eval_interval = eval_interval + self.eval_offset = eval_offset + + # Create and initialize the interval triggers. + self.eval_trigger = utils.IntervalTrigger(self.eval_interval, + self.eval_offset) + + if self.warmup_fn is not None: + self.device_warmup_steps = device_warmup_steps + + if self.global_step: + tf.summary.experimental.set_step(self.global_step) + + # Restore Model if needed. + if self.checkpoint_manager is not None: + model_restored = self._restore_model() + if not model_restored and self.checkpoint_manager.checkpoint_interval: + # If the model is not restored from a checkpoint, save an initial + # checkpoint. + ckpt_path = self.checkpoint_manager.save( + checkpoint_number=self.global_step) + logging.info("Saved checkpoins in %s", ckpt_path) + + def _restore_model(self, checkpoint_path=None): + """Restore or initialize the model. + + Args: + checkpoint_path: An optional string indicates the checkpoint path to + restore. If None, will restore from `self.checkpoint_manager`. + + Returns: + True if the latest checkpoint is found or restored. Otherwise False. + """ + with self.strategy.scope(): + # Checkpoint restoring should be inside scope. b/139450638 + if checkpoint_path is not None: + self.checkpoint_manager.checkpoint.restore(checkpoint_path) + return True + return self.checkpoint_manager.restore_or_initialize() + + def _evaluate_once(self, current_step): + """Runs the evaluation once.""" + logging.info("Start evaluation at step: %s", current_step) + + with self.eval_summary_manager.summary_writer.as_default(): + eval_outputs = self.eval_fn(self.eval_steps) + + if eval_outputs: + eval_outputs = tf.nest.map_structure( + lambda x: (x if isinstance(x, (float, bool)) else x.numpy()), + eval_outputs) + + info = "step: {} evaluation metric: {}".format( + current_step, eval_outputs) + self._log_info(info) + self.last_eval_output = eval_outputs + + self.eval_summary_manager.write_summaries(eval_outputs) + self.eval_summary_manager.flush() + if "continue_training" in eval_outputs.keys(): + return eval_outputs["continue_training"] + else: + return True + + def _maybe_save_checkpoints(self, current_step, force_trigger=False): + if self.checkpoint_manager.checkpoint_interval: + ckpt_path = self.checkpoint_manager.save( + checkpoint_number=current_step, check_interval=not force_trigger) + if ckpt_path is not None: + logging.info("Saved checkpoins in %s", ckpt_path) + + def _maybe_evaluate(self, current_step, force_trigger=False): + if self.eval_trigger(current_step, force_trigger): + return self._evaluate_once(current_step) + return True + + def _log_info(self, message): + """Logs `message` to the `info` log, and also prints to stdout.""" + logging.info(message) + print(message) + + def train(self, evaluate=True, num_acc_steps:int=1, manifest_path=None): + """Runs the training, with optional evaluation. + + This handles evaluation, gathering summaries, and saving checkpoints. + + Args: + evaluate: A boolean indicates whether to perform evaluation during + training. + num_acc_steps: Number of gradient accumulation steps. + + Raises: + RuntimeError: If `global_step` is not updated correctly in `train_fn`. + """ + if self.train_fn is None: + raise ValueError("`self.train_fn` is required when calling `train` " + "method.") + if self.global_step is None: + raise ValueError("`self.global_step` is required when calling `train` " + "method.") + if evaluate and self.eval_fn is None: + raise ValueError("`self.eval_fn` is required when calling `train` method " + "with `evaluate=True`") + + step_timer = _StepTimer(self.global_step) + current_step = self.global_step.numpy() + logging.info("Train at step %s of %s", current_step, self.train_steps) + while current_step < self.train_steps: + # Calculates steps to run for the next train loop. + steps_per_loop = min(self.train_steps - current_step, self.steps_per_loop) + logging.info("Entering training loop with %s steps, at step %s of %s", + steps_per_loop, current_step, self.train_steps) + current_step += steps_per_loop + steps_per_loop = tf.convert_to_tensor(steps_per_loop, dtype=tf.int32) + + with self.summary_manager.summary_writer.as_default(): + train_outputs = self.train_fn(steps_per_loop, num_acc_steps, manifest_path) + + # Updates and verifies the current step after a training loop finishes. + if current_step != self.global_step.numpy(): + raise RuntimeError("`self.train_fn` is not updating `global_step` " + "correctly, expected: %s, actual: %s" % + (current_step, self.global_step.numpy())) + + # Print information like metrics and steps_per_second after a training + # loop. + if train_outputs: + train_outputs = tf.nest.map_structure( + lambda x: x.numpy(), train_outputs) + steps_per_second = step_timer.steps_per_second() + info = "step: {} steps_per_second: {:.2f} {}".format( + current_step, steps_per_second, train_outputs) + self._log_info(info) + + train_outputs = train_outputs or {} + train_outputs["steps_per_second"] = steps_per_second + self.summary_manager.write_summaries(train_outputs) + + self._maybe_save_checkpoints(current_step) + + if evaluate: + continue_training = self._maybe_evaluate(current_step) + if not continue_training: + break + + self.summary_manager.write_summaries(train_outputs, always_write=True) + self.summary_manager.flush() + self._maybe_save_checkpoints(current_step, force_trigger=True) + + def evaluate(self, continuous=False, timeout_fn=None): + """Runs the evaluation. + + Args: + continuous: If `True`, will continously monitor the checkpoint directory + to evaluate on the latest checkpoint. If `False`, will do the evaluation + once. + timeout_fn: Optional callable to call after a timeout. If the function + returns True, then it means that no new checkpoints will be generated + and the iterator will exit. + + Raises: + ValueError: If no checkpoint found in `self.checkpoint_manager.directory`. + """ + if self.eval_fn is None: + raise ValueError("`self.eval_fn` should not be None to call " + "`evaluate()` method.") + + if not continuous and timeout_fn is not None: + raise ValueError("`timeout_fn` can be only passed when `continuous` is " + "True") + + if continuous: + for checkpoint_path in tf.train.checkpoints_iterator( + self.checkpoint_manager.directory, timeout_fn=timeout_fn): + self._restore_model(checkpoint_path) + self._evaluate_once(self.global_step.numpy()) + return + + latest_checkpoint = self.checkpoint_manager.latest_checkpoint + if not latest_checkpoint: + raise ValueError("no checkpoint found in dir %s" % + self.checkpoint_manager.directory) + self._restore_model() + self._evaluate_once(self.global_step.numpy()) + + def warmup(self): + """Runs device warmup. + + This handles running a training loop on dummy data to move TF function + compilation outside of the training loop. + + """ + if self.global_step is None: + raise ValueError("`self.global_step` is required when calling `warmup` " + "method.") + + step_timer = _StepTimer(self.global_step) + current_step = self.global_step.numpy() + logging.info("Warmup at step %s of %s", current_step, + self.device_warmup_steps) + while current_step < self.device_warmup_steps: + # Calculates steps to run for the next train loop. + steps_per_loop = self.device_warmup_steps + logging.info("Entering warmup loop with %s steps, at step %s of %s", + steps_per_loop, current_step, self.device_warmup_steps) + current_step += steps_per_loop + steps_per_loop = tf.convert_to_tensor(steps_per_loop, dtype=tf.int32) + + with self.summary_manager.summary_writer.as_default(): + self.warmup_fn(steps_per_loop) + + steps_per_second = step_timer.steps_per_second() + info = "step: {} steps_per_second: {:.2f}".format( + current_step, steps_per_second) + self._log_info(info) + +class _StepTimer(object): + """Utility class for measuring steps/second.""" + + def __init__(self, step): + self.step = step + self.start() + + def start(self): + self.last_iteration = self.step.numpy() + self.last_time = time.time() + + def steps_per_second(self, restart=True): + value = ((self.step.numpy() - self.last_iteration) / + (time.time() - self.last_time)) + if restart: + self.start() + return value diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/grad_utils.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/grad_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..16f13db938bd184ae4231b13ff4a4c82eeb20fdb --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/grad_utils.py @@ -0,0 +1,143 @@ +# Copyright 2019 The TensorFlow Authors. 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. +# ============================================================================== +"""Some gradient util functions to help users writing custom training loop.""" + +from __future__ import absolute_import +from __future__ import division +# from __future__ import google_type_annotations +from __future__ import print_function + +from absl import logging + +import tensorflow.compat.v2 as tf + + +def _filter_grads(grads_and_vars): + """Filter out iterable with grad equal to None.""" + grads_and_vars = tuple(grads_and_vars) + if not grads_and_vars: + return grads_and_vars + filtered = [] + vars_with_empty_grads = [] + for grad, var in grads_and_vars: + if grad is None: + vars_with_empty_grads.append(var) + else: + filtered.append((grad, var)) + filtered = tuple(filtered) + if not filtered: + raise ValueError("No gradients provided for any variable: %s." % + ([v.name for _, v in grads_and_vars],)) + if vars_with_empty_grads: + logging.warning( + ("Gradients do not exist for variables %s when minimizing the loss."), + ([v.name for v in vars_with_empty_grads])) + return filtered + + +def _filter_and_allreduce_gradients(grads_and_vars, + allreduce_precision="float32"): + """Filter None grads and then allreduce gradients in specified precision. + + This utils function is used when users intent to explicitly allreduce + gradients and customize gradients operations before and after allreduce. + The allreduced gradients are then passed to optimizer.apply_gradients( + experimental_aggregate_gradients=False). + + Arguments: + grads_and_vars: gradients and variables pairs. + allreduce_precision: Whether to allreduce gradients in float32 or float16. + + Returns: + pairs of allreduced non-None gradients and variables. + """ + filtered_grads_and_vars = _filter_grads(grads_and_vars) + (grads, variables) = zip(*filtered_grads_and_vars) + if allreduce_precision == "float16": + grads = [tf.cast(grad, "float16") for grad in grads] + allreduced_grads = tf.distribute.get_replica_context().all_reduce( + tf.distribute.ReduceOp.SUM, grads) + if allreduce_precision == "float16": + allreduced_grads = [tf.cast(grad, "float32") for grad in allreduced_grads] + return allreduced_grads, variables + + +def _run_callbacks(callbacks, grads_and_vars): + for callback in callbacks: + grads_and_vars = callback(grads_and_vars) + return grads_and_vars + + +def minimize_using_explicit_allreduce(tape, + optimizer, + loss, + trainable_variables, + pre_allreduce_callbacks=None, + post_allreduce_callbacks=None): + """Minimizes loss for one step by updating `trainable_variables`. + + Minimizes loss for one step by updating `trainable_variables`. + This explicitly performs gradient allreduce, instead of relying on implicit + allreduce in optimizer.apply_gradients(). If training using FP16 mixed + precision, explicit allreduce will aggregate gradients in FP16 format. + For TPU and GPU training using FP32, explicit allreduce will aggregate + gradients in FP32 format. + + Arguments: + tape: An instance of `tf.GradientTape`. + optimizer: An instance of `tf.keras.optimizers.Optimizer`. + loss: the loss tensor. + trainable_variables: A list of model Variables. + pre_allreduce_callbacks: A list of callback functions that takes gradients + and model variables pairs as input, manipulate them, and returns a new + gradients and model variables pairs. The callback functions will be + invoked in the list order and before gradients are allreduced. + With mixed precision training, the pre_allreduce_allbacks will be + applied on scaled_gradients. Default is no callbacks. + post_allreduce_callbacks: A list of callback functions that takes + gradients and model variables pairs as input, manipulate them, and + returns a new gradients and model variables paris. The callback + functions will be invoked in the list order and right before gradients + are applied to variables for updates. Default is no callbacks. + """ + if isinstance(optimizer, + tf.keras.mixed_precision.LossScaleOptimizer): + # FP16 GPU code path + with tape: + scaled_loss = optimizer.get_scaled_loss(loss) + scaled_grads = tape.gradient(scaled_loss, trainable_variables) + grads_and_vars = zip(scaled_grads, trainable_variables) + if pre_allreduce_callbacks: + grads_and_vars = _run_callbacks(pre_allreduce_callbacks, grads_and_vars) + (allreduced_scaled_grads, + filtered_training_vars) = _filter_and_allreduce_gradients( + grads_and_vars, allreduce_precision="float16") + allreduced_unscaled_grads = optimizer.get_unscaled_gradients( + allreduced_scaled_grads) + grads_and_vars = zip(allreduced_unscaled_grads, filtered_training_vars) + else: + # TPU or FP32 GPU code path + grads = tape.gradient(loss, trainable_variables) + grads_and_vars = zip(grads, trainable_variables) + if pre_allreduce_callbacks: + grads_and_vars = _run_callbacks(pre_allreduce_callbacks, grads_and_vars) + (allreduced_grads, + filtered_training_vars) = _filter_and_allreduce_gradients( + grads_and_vars, allreduce_precision="float32") + grads_and_vars = zip(allreduced_grads, filtered_training_vars) + if post_allreduce_callbacks: + grads_and_vars = _run_callbacks(post_allreduce_callbacks, grads_and_vars) + optimizer.apply_gradients( + grads_and_vars, experimental_aggregate_gradients=False) diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/runnable.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/runnable.py new file mode 100644 index 0000000000000000000000000000000000000000..1af6eca06a337506a68d6329e0da16c9ca095e0a --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/runnable.py @@ -0,0 +1,79 @@ +# Copyright 2019 The TensorFlow Authors. 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. +# ============================================================================== +"""An abstraction that users can easily handle their custom training loops.""" + +from __future__ import absolute_import +from __future__ import division +# from __future__ import google_type_annotations +from __future__ import print_function + +import abc +import six +import tensorflow.compat.v2 as tf +from typing import Dict, Optional, Text + + +@six.add_metaclass(abc.ABCMeta) +class AbstractTrainable(tf.Module): + """An abstract class defining the APIs required for training.""" + + @abc.abstractmethod + def train(self, + num_steps: Optional[tf.Tensor]) -> Optional[Dict[Text, tf.Tensor]]: + """Implements model training with multiple steps. + + In training, it is common to break the total training steps into several + training loops, so users can do checkpointing, write summaries and run some + python callbacks. This is necessary for getting good performance in TPU + training, as the overhead for launching a multi worker tf.function may be + large in Eager mode. It is usually encouraged to create a host training loop + (e.g. using a `tf.range` wrapping `strategy.run` inside a + `tf.function`) in the TPU case. For the cases that don't require host + training loop to acheive peak performance, users can just implement a simple + python loop to drive each step. + + Args: + num_steps: A guideline for how many training steps to run. Note that it is + up to the model what constitutes a "step" (this may involve more than + one update to model parameters, e.g. if training a GAN). + + Returns: + The function may return a dictionary of `Tensors`, which will be + written to logs and as TensorBoard summaries. + """ + pass + + +@six.add_metaclass(abc.ABCMeta) +class AbstractEvaluable(tf.Module): + """An abstract class defining the APIs required for evaluation.""" + + @abc.abstractmethod + def evaluate( + self, num_steps: Optional[tf.Tensor]) -> Optional[Dict[Text, tf.Tensor]]: + """Implements model evaluation. + + Args: + num_steps: A guideline for how many evaluation steps to run. Note that it + is up to the model what constitutes a "step". Generally, it may be + desirable to support both a limited number of eval steps and iterating + over a full dataset (however many steps are required) when `num_steps` + is `None`. + + Returns: + The function may return a dictionary of `Tensors`, which will be + written to logs and as TensorBoard summaries. + """ + pass diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/standard_runnable.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/standard_runnable.py new file mode 100644 index 0000000000000000000000000000000000000000..e2bb8f00be232c586bea67d0ffb8c2c66e1ac325 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/standard_runnable.py @@ -0,0 +1,183 @@ +# Copyright 2019 The TensorFlow Authors. 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. +# ============================================================================== +"""An abstraction that users can easily handle their custom training loops.""" + +from __future__ import absolute_import +from __future__ import division +# from __future__ import google_type_annotations +from __future__ import print_function + +import abc +import six +import tensorflow.compat.v2 as tf +from typing import Dict, Optional, Text + +from TensorFlow.common.training import runnable +from TensorFlow.common.training import utils + + +@six.add_metaclass(abc.ABCMeta) +class StandardTrainable(runnable.AbstractTrainable): + """Implements the standard functionality of AbstractTrainable APIs.""" + + def __init__(self, use_tf_while_loop=True, use_tf_function=True): + if use_tf_while_loop and not use_tf_function: + raise ValueError("`use_tf_while_loop=True` and `use_tf_function=False` " + "is not supported") + self.use_tf_while_loop = use_tf_while_loop + self.use_tf_function = use_tf_function + self.train_dataset = None + self.train_iter = None + self.train_loop_fn = None + + @abc.abstractmethod + def build_train_dataset(self, manifest_path=None): + """Builds the training datasets. + + Returns: + A tf.nest-compatible structure of tf.data.Dataset or DistributedDataset. + """ + pass + + def train(self, num_steps: Optional[tf.Tensor], num_acc_steps:int=1, manifest_path=None) -> Optional[Dict[Text, tf.Tensor]]: + """See base class.""" + if self.train_dataset is None: + # Build train input dataset + self.train_dataset = self.build_train_dataset(manifest_path=manifest_path) + self.train_iter = tf.nest.map_structure(iter, self.train_dataset) + + if self.train_loop_fn is None: + train_fn = self.train_step + if self.use_tf_while_loop: + self.train_loop_fn = utils.create_tf_while_loop_fn(train_fn) + else: + if self.use_tf_function: + train_fn = tf.function(train_fn) + self.train_loop_fn = utils.create_loop_fn(train_fn) + + self.train_loop_begin() + self.train_loop_fn(self.train_iter, num_steps, num_acc_steps) + return self.train_loop_end() + + def train_loop_begin(self): + """Called once at the beginning of the training loop. + + This is a good place to reset metrics that accumulate values over multiple + steps of training. + """ + pass + + @abc.abstractmethod + def train_step(self, iterator): + """Implements one step of training. + + What a "step" consists of is up to the implementer. If using distribution + strategies, the call to this method should take place in the "cross-replica + context" for generality, to allow e.g. multiple iterator dequeues and calls + to `strategy.run`. + + Args: + iterator: A tf.nest-compatible structure of tf.data Iterator or + DistributedIterator. + """ + pass + + def train_loop_end(self) -> Optional[Dict[Text, tf.Tensor]]: + """Called at the end of the training loop. + + This is a good place to get metric results. The value returned from this + function will be returned as-is from the train() method. + + Returns: + The function may return a dictionary of `Tensors`, which will be + written to logs and as TensorBoard summaries. + """ + pass + + +@six.add_metaclass(abc.ABCMeta) +class StandardEvaluable(runnable.AbstractEvaluable): + """Implements the standard functionality of AbstractEvaluable APIs.""" + + def __init__(self, use_tf_function=True): + self.eval_use_tf_function = use_tf_function + self.eval_dataset = None + self.eval_loop_fn = None + + @abc.abstractmethod + def build_eval_dataset(self): + """Builds the evaluation datasets. + + Returns: + A tf.nest-compatible structure of tf.data.Dataset or DistributedDataset. + """ + pass + + def evaluate( + self, num_steps: Optional[tf.Tensor]) -> Optional[Dict[Text, tf.Tensor]]: + """See base class.""" + if self.eval_dataset is None: + # Build train input dataset + self.eval_dataset = self.build_eval_dataset() + + if self.eval_loop_fn is None: + eval_fn = self.eval_step + if self.eval_use_tf_function: + eval_fn = tf.function(eval_fn) + self.eval_loop_fn = utils.create_loop_fn(eval_fn) + + # TODO(b/147718615): When async RPC is enabled in eager runtime, we make + # eval iterator as a class member so it doesn't get destroyed when out of + # the function scope. + self.eval_iter = tf.nest.map_structure(iter, self.eval_dataset) + + self.eval_begin() + self.eval_loop_fn(self.eval_iter, num_steps) + return self.eval_end() + + def eval_begin(self): + """Called once at the beginning of the evaluation. + + This is a good place to reset metrics that accumulate values over the entire + evaluation. + """ + pass + + @abc.abstractmethod + def eval_step(self, iterator): + """Implements one step of evaluation. + + What a "step" consists of is up to the implementer. If using distribution + strategies, the call to this method should take place in the "cross-replica + context" for generality, to allow e.g. multiple iterator dequeues and calls + to `strategy.run`. + + Args: + iterator: A tf.nest-compatible structure of tf.data Iterator or + DistributedIterator. + """ + pass + + def eval_end(self) -> Optional[Dict[Text, tf.Tensor]]: + """Called at the end of the evaluation. + + This is a good place to get metric results. The value returned from this + function will be returned as-is from the evaluate() method. + + Returns: + The function may return a dictionary of `Tensors`, which will be + written to logs and as TensorBoard summaries. + """ + pass diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/utils.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..367ecd96b1982b8749561679ab9e718df73b1040 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/utils.py @@ -0,0 +1,344 @@ +# Copyright 2019 The TensorFlow Authors. 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. +# ============================================================================== +"""Some layered modules/functions to help users writing custom training loop.""" + +from __future__ import absolute_import +from __future__ import division +# from __future__ import google_type_annotations +from __future__ import print_function + +import abc +import inspect +import six + +import tensorflow.compat.v2 as tf + + +def create_loop_fn(step_fn): + """Creates a multiple steps function driven by the python while loop. + + Args: + step_fn: A function which takes `iterator` as input. + + Returns: + A callable defined as the `loop_fn` defination below. + """ + + def loop_fn(iterator, num_steps, state=None, reduce_fn=None): + """A loop function with multiple steps. + + Args: + iterator: A nested structure of tf.data `Iterator` or + `DistributedIterator`. + num_steps: The number of steps in the loop. If `num_steps==-1`, will + iterate until exausting the iterator. + state: An optional initial state before running the loop. + reduce_fn: a callable defined as `def reduce_fn(state, value)`, where + `value` is the outputs from `step_fn`. + + Returns: + The updated state. + """ + try: + step = 0 + # To make sure the OutOfRangeError exception can be handled well with + # async remote eager, we need to wrap the loop body in a `async_scope`. + with tf.experimental.async_scope(): + while (num_steps == -1 or step < num_steps): + outputs = step_fn(iterator) + if reduce_fn is not None: + state = reduce_fn(state, outputs) + step += 1 + return state + except (StopIteration, tf.errors.OutOfRangeError): + tf.experimental.async_clear_error() + return state + + return loop_fn + + +def create_tf_while_loop_fn(step_fn): + """Create a multiple steps function driven by tf.while_loop on the host. + + Args: + step_fn: A function which takes `iterator` as input. + + Returns: + A callable defined as the `loop_fn` defination below. + """ + + @tf.function + def loop_fn(iterator, num_steps, num_acc_steps:int=1): + """A loop function with multiple steps. + + Args: + iterator: A nested structure of tf.data `Iterator` or + `DistributedIterator`. + num_steps: The number of steps in the loop. Must be a tf.Tensor. + num_acc_steps: Number of gradient accumulation steps. + """ + if not isinstance(num_steps, tf.Tensor): + raise ValueError("`num_steps` should be an `tf.Tensor`. Python object " + "may cause retracing.") + + for _ in tf.range(num_steps): + for _ in range(num_acc_steps): + step_fn(iterator) + + return loop_fn + + +def make_distributed_dataset(strategy, dataset_or_fn, *args, **kwargs): + """A helper function to create distributed dataset. + + Args: + strategy: An instance of `tf.distribute.Strategy`. + dataset_or_fn: A instance of `tf.data.Dataset` or a function which takes an + `tf.distribute.InputContext` as input and returns a `tf.data.Dataset`. If + it is a function, it could optionally have an argument named + `input_context` which is `tf.distribute.InputContext` argument type. + *args: The list of arguments to be passed to dataset_or_fn. + **kwargs: Any keyword arguments to be passed. + + Returns: + A distributed Dataset. + """ + if strategy is None: + strategy = tf.distribute.get_strategy() + + if isinstance(dataset_or_fn, tf.data.Dataset): + return strategy.experimental_distribute_dataset(dataset_or_fn) + + if not callable(dataset_or_fn): + raise ValueError("`dataset_or_fn` should be either callable or an instance " + "of `tf.data.Dataset`") + + def dataset_fn(ctx): + """Wrapped dataset function for creating distributed dataset..""" + + # If `dataset_or_fn` is a function and has `input_context` as argument + # names, pass `ctx` as the value of `input_context` when calling + # `dataset_or_fn`. Otherwise `ctx` will not be used when calling + # `dataset_or_fn`. + if six.PY3: + argspec = inspect.getfullargspec(dataset_or_fn) + else: + argspec = inspect.getargspec(dataset_or_fn) + args_names = argspec.args + + if "input_context" in args_names: + kwargs["input_context"] = ctx + ds = dataset_or_fn(*args, **kwargs) + return ds + + return strategy.experimental_distribute_datasets_from_function(dataset_fn) + + +class SummaryManager(object): + """A class manages writing summaries.""" + + def __init__(self, + summary_writer, + summary_fn, + global_step=None, + summary_interval=None): + """Construct a summary manager object. + + Args: + summary_writer: A `tf.summary.SummaryWriter` instance for writing + summaries. + summary_fn: A callable defined as `def summary_fn(name, tensor, + step=None)`, which describes the summary operation. + global_step: A `tf.Variable` instance for checking the current global step + value, in case users want to save summaries every N steps. + summary_interval: An integer, indicates the minimum step interval between + two summaries. + """ + if summary_writer is not None: + self._summary_writer = summary_writer + self._enabled = True + else: + self._summary_writer = tf.summary.create_noop_writer() + self._enabled = False + self._summary_fn = summary_fn + + if global_step is None: + self._global_step = tf.summary.experimental.get_step() + else: + self._global_step = global_step + + if summary_interval is not None: + if self._global_step is None: + raise ValueError("`summary_interval` is not None, but no `global_step` " + "can be obtained ") + self._last_summary_step = self._global_step.numpy() + self._summary_interval = summary_interval + + @property + def summary_interval(self): + return self._summary_interval + + @property + def summary_writer(self): + """Returns the underlying summary writer.""" + return self._summary_writer + + def flush(self): + """Flush the underlying summary writer.""" + if self._enabled: + tf.summary.flush(self._summary_writer) + + def write_summaries(self, items, always_write=True): + """Write a bulk of summaries. + + Args: + items: a dictionary of `Tensors` for writing summaries. + always_write: An optional boolean. If `True`, the manager will always + write summaries unless the summaries have been written for the same + step. Otherwise the manager will only write the summaries if the + interval between summaries are larger than `summary_interval`. + + Returns: + A boolean indicates whether the summaries are written or not. + """ + # TODO(rxsang): Support writing summaries with nested structure, so users + # can split the summaries into different directories for nicer visualization + # in Tensorboard, like train and eval metrics. + if not self._enabled: + return False + + if self._summary_interval is not None: + current_step = self._global_step.numpy() + if current_step == self._last_summary_step: + return False + if not always_write and current_step < (self._last_summary_step + + self._summary_interval): + return False + self._last_summary_step = current_step + + with self._summary_writer.as_default(): + for name, tensor in items.items(): + self._summary_fn(name, tensor, step=self._global_step) + return True + + +@six.add_metaclass(abc.ABCMeta) +class Trigger(object): + """An abstract class representing a "trigger" for some event.""" + + @abc.abstractmethod + def __call__(self, value: float, force_trigger=False): + """Maybe trigger the event based on the given value. + + Args: + value: the value for triggering. + force_trigger: Whether the trigger is forced triggered. + + Returns: + `True` if the trigger is triggered on the given `value`, and + `False` otherwise. + """ + + @abc.abstractmethod + def reset(self): + """Reset states in the trigger.""" + + +class IntervalTrigger(Trigger): + """Triggers on every fixed interval.""" + + def __init__(self, interval, start=0): + """Constructs the IntervalTrigger. + + Args: + interval: The triggering interval. + start: An initial value for the trigger. + """ + self._interval = interval + self._last_trigger_value = start + + def __call__(self, value, force_trigger=False): + """Maybe trigger the event based on the given value. + + Args: + value: the value for triggering. + force_trigger: If True, the trigger will be forced triggered unless the + last trigger value is equal to `value`. + + Returns: + `True` if the trigger is triggered on the given `value`, and + `False` otherwise. + """ + if force_trigger and value != self._last_trigger_value: + self._last_trigger_value = value + return True + + if self._interval and self._interval > 0: + if value >= self._last_trigger_value + self._interval: + self._last_trigger_value = value + return True + return False + + def reset(self): + """See base class.""" + self._last_trigger_value = 0 + + +class EpochHelper(object): + """A Helper class to handle epochs in Customized Training Loop.""" + + def __init__(self, epoch_steps, global_step): + """Constructs the EpochHelper. + + Args: + epoch_steps: An integer indicates how many steps in an epoch. + global_step: A `tf.Variable` instance indicates the current global step. + """ + self._epoch_steps = epoch_steps + self._global_step = global_step + self._current_epoch = None + self._epoch_start_step = None + self._in_epoch = False + + def epoch_begin(self): + """Returns whether a new epoch should begin.""" + if self._in_epoch: + return False + current_step = self._global_step.numpy() + self._epoch_start_step = current_step + self._current_epoch = current_step // self._epoch_steps + self._in_epoch = True + return True + + def epoch_end(self): + """Returns whether the current epoch should end.""" + if not self._in_epoch: + raise ValueError("`epoch_end` can only be called inside an epoch") + current_step = self._global_step.numpy() + epoch = current_step // self._epoch_steps + + if epoch > self._current_epoch: + self._in_epoch = False + return True + return False + + @property + def batch_index(self): + """Index of the next batch within the current epoch.""" + return self._global_step.numpy() - self._epoch_start_step + + @property + def current_epoch(self): + return self._current_epoch diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/__init__.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/common.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/common.py new file mode 100644 index 0000000000000000000000000000000000000000..db8f12d6a6dd4dc6eef3d953e7956975ebb9f239 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/common.py @@ -0,0 +1,523 @@ +# Copyright 2018 The TensorFlow Authors. 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. +# ============================================================================== +# List of changes: +# - added Habana specific flags +# - added helper function for prefetching + +# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company + +"""Common util functions and classes used by both keras cifar and imagenet.""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os + +from absl import flags +import tensorflow as tf + +import tensorflow_model_optimization as tfmot +from TensorFlow.utils.flags import core as flags_core +from TensorFlow.utils.misc import keras_utils +from TensorFlow.utils.flags._conventions import help_wrap +from habana_frameworks.tensorflow.multinode_helpers import comm_size +from TensorFlow.common.tb_utils import ( + ExamplesPerSecondKerasHook, TensorBoardWithHParamsV1) + +from TensorFlow.computer_vision.common import imagenet_preprocessing +from TensorFlow.computer_vision.Resnets.utils.optimizers.keras import lars_optimizer +from TensorFlow.computer_vision.Resnets.utils.optimizers.keras import lars_util + +try: + import horovod.tensorflow as hvd +except ImportError: + hvd = None + +FLAGS = flags.FLAGS +BASE_LEARNING_RATE = 0.1 # This matches Jing's version. +TRAIN_TOP_1 = 'training_accuracy_top_1' +LR_SCHEDULE = [ # (multiplier, epoch to start) tuples + (1.0, 5), (0.1, 30), (0.01, 60), (0.001, 80) +] + +global_batch_size = None +def get_global_batch_size(batch_size, num_acc_steps:int=1): + global global_batch_size + if global_batch_size is None: + global_batch_size = batch_size + if hvd is not None and hvd.is_initialized(): + global_batch_size = batch_size * comm_size() + global_batch_size = global_batch_size * num_acc_steps + return global_batch_size + +class PiecewiseConstantDecayWithWarmup( + tf.keras.optimizers.schedules.LearningRateSchedule): + """Piecewise constant decay with warmup schedule.""" + + def __init__(self, batch_size, epoch_size, warmup_epochs, boundaries, + multipliers, compute_lr_on_cpu=False, name=None): + super(PiecewiseConstantDecayWithWarmup, self).__init__() + if len(boundaries) != len(multipliers) - 1: + raise ValueError('The length of boundaries must be 1 less than the ' + 'length of multipliers') + + base_lr_batch_size = 256 + steps_per_epoch = epoch_size // batch_size + + self.rescaled_lr = BASE_LEARNING_RATE * batch_size / base_lr_batch_size + self.step_boundaries = [float(steps_per_epoch) * x for x in boundaries] + self.lr_values = [self.rescaled_lr * m for m in multipliers] + self.warmup_steps = warmup_epochs * steps_per_epoch + self.compute_lr_on_cpu = compute_lr_on_cpu + self.name = name + + self.learning_rate_ops_cache = {} + + def __call__(self, step): + if tf.executing_eagerly(): + return self._get_learning_rate(step) + + # In an eager function or graph, the current implementation of optimizer + # repeatedly call and thus create ops for the learning rate schedule. To + # avoid this, we cache the ops if not executing eagerly. + graph = tf.compat.v1.get_default_graph() + if graph not in self.learning_rate_ops_cache: + if self.compute_lr_on_cpu: + with tf.device('/device:CPU:0'): + self.learning_rate_ops_cache[graph] = self._get_learning_rate(step) + else: + self.learning_rate_ops_cache[graph] = self._get_learning_rate(step) + return self.learning_rate_ops_cache[graph] + + def _get_learning_rate(self, step): + """Compute learning rate at given step.""" + with tf.compat.v1.name_scope(self.name, 'PiecewiseConstantDecayWithWarmup', + [self.rescaled_lr, self.step_boundaries, + self.lr_values, self.warmup_steps, + self.compute_lr_on_cpu]): + def warmup_lr(step): + return self.rescaled_lr * ( + tf.cast(step, tf.float32) / tf.cast(self.warmup_steps, tf.float32)) + def piecewise_lr(step): + return tf.compat.v1.train.piecewise_constant( + step, self.step_boundaries, self.lr_values) + return tf.cond(step < self.warmup_steps, + lambda: warmup_lr(step), + lambda: piecewise_lr(step)) + + def get_config(self): + return { + 'rescaled_lr': self.rescaled_lr, + 'step_boundaries': self.step_boundaries, + 'lr_values': self.lr_values, + 'warmup_steps': self.warmup_steps, + 'compute_lr_on_cpu': self.compute_lr_on_cpu, + 'name': self.name + } + + +def get_lr_schedule(flags_obj, global_batch_size, train_steps,mlperf_mlloger,mlperf_mllog): + lr_schedule = None + + if flags_obj.lr_schedule == 'polynomial': + lr_schedule = lars_util.PolynomialDecayWithWarmup( + batch_size=global_batch_size, + steps_per_epoch=imagenet_preprocessing.NUM_IMAGES['train'] // global_batch_size, + train_steps=train_steps, + initial_learning_rate=flags_obj.base_learning_rate, + end_learning_rate=flags_obj.end_learning_rate, + warmup_epochs=flags_obj.warmup_epochs, + mlperf_mlloger=mlperf_mlloger, + mlperf_mllog=mlperf_mllog) + elif flags_obj.lr_schedule == 'piecewise': + lr_schedule = PiecewiseConstantDecayWithWarmup( + batch_size=global_batch_size, + epoch_size=imagenet_preprocessing.NUM_IMAGES['train'], + warmup_epochs=LR_SCHEDULE[0][1], + boundaries=list(p[1] for p in LR_SCHEDULE[1:]), + multipliers=list(p[0] for p in LR_SCHEDULE), + compute_lr_on_cpu=False) + elif flags_obj.lr_schedule == 'constant': + lr_schedule = flags_obj.base_learning_rate * global_batch_size / 256 + else: + raise ValueError('lr_schedule "%s" is unknown.' % flags_obj.lr_schedule) + + return lr_schedule + + +def get_optimizer(flags_obj, global_batch_size, train_steps,mlperf_mlloger,mlperf_mllog): + optimizer = None + lr_schedule = get_lr_schedule(flags_obj, global_batch_size, train_steps,mlperf_mlloger,mlperf_mllog) + + if flags_obj.optimizer == 'SGD': + # The learning_rate is overwritten at the beginning of each step by callback. + optimizer = tf.keras.optimizers.legacy.SGD(learning_rate=lr_schedule, momentum=0.9) + + elif flags_obj.optimizer == 'LARS': + optimizer = lars_optimizer.LARSOptimizer( + learning_rate=lr_schedule, + momentum=flags_obj.momentum, + weight_decay=flags_obj.weight_decay, + skip_list=['batch_normalization', 'bias', 'bn'], + epsilon=flags_obj.lars_epsilon) + else: + raise ValueError('optimizer "%s" is unknown.' % flags_obj.optimizer) + + return optimizer + + +def get_callbacks( + steps_per_epoch, + pruning_method=None, + enable_checkpoint_and_export=False, + model_dir=None): + """Returns common callbacks.""" + time_callback = keras_utils.TimeHistory( + FLAGS.batch_size, + FLAGS.log_steps, + logdir=FLAGS.model_dir if FLAGS.enable_tensorboard else None) + callbacks = [time_callback] + + if FLAGS.enable_tensorboard: + callbacks += [ + TensorBoardWithHParamsV1( + FLAGS.flag_values_dict(), + log_dir=FLAGS.model_dir, + update_freq=FLAGS.log_steps), + ExamplesPerSecondKerasHook( + output_dir=FLAGS.model_dir, + every_n_steps=FLAGS.log_steps) + ] + + if FLAGS.profile_steps: + profiler_callback = keras_utils.get_profiler_callback( + FLAGS.model_dir, + FLAGS.profile_steps, + FLAGS.enable_tensorboard, + steps_per_epoch) + callbacks.append(profiler_callback) + + is_pruning_enabled = pruning_method is not None + + if is_pruning_enabled: + callbacks.append(tfmot.sparsity.keras.UpdatePruningStep()) + if model_dir is not None: + callbacks.append(tfmot.sparsity.keras.PruningSummaries( + log_dir=model_dir, profile_batch=0)) + + if enable_checkpoint_and_export: + if model_dir is not None: + ckpt_full_path = os.path.join(model_dir, 'model.ckpt-{epoch:04d}') + callbacks.append( + tf.keras.callbacks.ModelCheckpoint(ckpt_full_path, + save_weights_only=True)) + return callbacks + + +def build_stats(history, eval_output, callbacks): + """Normalizes and returns dictionary of stats. + + Args: + history: Results of the training step. Supports both categorical_accuracy + and sparse_categorical_accuracy. + eval_output: Output of the eval step. Assumes first value is eval_loss and + second value is accuracy_top_1. + callbacks: a list of callbacks which might include a time history callback + used during keras.fit. + + Returns: + Dictionary of normalized results. + """ + stats = {} + if eval_output: + stats['accuracy_top_1'] = float(eval_output[1]) + stats['eval_loss'] = float(eval_output[0]) + if history and history.history: + train_hist = history.history + # Gets final loss from training. + stats['loss'] = float(train_hist['loss'][-1]) + # Gets top_1 training accuracy. + if 'categorical_accuracy' in train_hist: + stats[TRAIN_TOP_1] = float(train_hist['categorical_accuracy'][-1]) + elif 'sparse_categorical_accuracy' in train_hist: + stats[TRAIN_TOP_1] = float(train_hist['sparse_categorical_accuracy'][-1]) + elif 'accuracy' in train_hist: + stats[TRAIN_TOP_1] = float(train_hist['accuracy'][-1]) + + if not callbacks: + return stats + + # Look for the time history callback which was used during keras.fit + for callback in callbacks: + if isinstance(callback, keras_utils.TimeHistory): + timestamp_log = callback.timestamp_log + stats['step_timestamp_log'] = timestamp_log + stats['train_finish_time'] = callback.train_finish_time + if callback.epoch_runtime_log: + stats['avg_exp_per_second'] = callback.average_examples_per_second + + return stats + + +def define_keras_flags( + dynamic_loss_scale=True, + model=False, + optimizer=False, + pretrained_filepath=False): + """Define flags for Keras models.""" + flags_core.define_base(clean=True, num_gpu=True, run_eagerly=True, + train_epochs=True, epochs_between_evals=True, + distribution_strategy=True) + flags_core.define_performance(num_parallel_calls=False, + synthetic_data=True, + dtype=True, + all_reduce_alg=True, + num_packs=True, + tf_gpu_thread_mode=True, + datasets_num_private_threads=True, + dynamic_loss_scale=dynamic_loss_scale, + loss_scale=True, + fp16_implementation=True, + tf_data_experimental_slack=True, + enable_xla=True, + dataset_cache=True) + flags_core.define_image() + flags_core.define_benchmark() + flags_core.define_distribution() + flags.adopt_module_key_flags(flags_core) + + flags.DEFINE_boolean(name='enable_eager', default=False, help='Enable eager?') + flags.DEFINE_boolean(name='skip_eval', default=False, help='Skip evaluation?') + # TODO(b/135607288): Remove this flag once we understand the root cause of + # slowdown when setting the learning phase in Keras backend. + flags.DEFINE_boolean( + name='set_learning_phase_to_train', default=True, + help='If skip eval, also set Keras learning phase to 1 (training).') + flags.DEFINE_boolean( + name='explicit_gpu_placement', default=False, + help='If not using distribution strategy, explicitly set device scope ' + 'for the Keras training loop.') + flags.DEFINE_boolean(name='use_trivial_model', default=False, + help='Whether to use a trivial Keras model.') + flags.DEFINE_boolean(name='report_accuracy_metrics', default=True, + help='Report metrics during training and evaluation.') + flags.DEFINE_boolean(name='use_tensor_lr', default=True, + help='Use learning rate tensor instead of a callback.') + flags.DEFINE_string( + name='lr_schedule', + default='piecewise', + help='learning rate schedule. ' + '"piecewise" for PiecewiseConstantDecayWithWarmup, ' + '"polynomial" for PolynomialDecayWithWarmup, ' + 'and "constant" for static learning rate.') + flags.DEFINE_boolean( + name='enable_tensorboard', default=False, + help='Whether to enable Tensorboard callback.') + flags.DEFINE_integer( + name='train_steps', default=None, + help='The number of steps to run for training. If it is larger than ' + '# batches per epoch, then use # batches per epoch. This flag will be ' + 'ignored if train_epochs is set to be larger than 1. ') + flags.DEFINE_string( + name='profile_steps', default=None, + help='Save profiling data to model dir at given range of global steps. The ' + 'value must be a comma separated pair of positive integers, specifying ' + 'the first and last step to profile. For example, "--profile_steps=2,4" ' + 'triggers the profiler to process 3 steps, starting from the 2nd step. ' + 'Note that profiler has a non-trivial performance overhead, and the ' + 'output file can be gigantic if profiling many steps.') + flags.DEFINE_boolean( + name='batchnorm_spatial_persistent', default=True, + help='Enable the spacial persistent mode for CuDNN batch norm kernel.') + flags.DEFINE_boolean( + name='enable_get_next_as_optional', default=False, + help='Enable get_next_as_optional behavior in DistributedIterator.') + flags.DEFINE_boolean( + name='enable_checkpoint_and_export', default=False, + help='Whether to enable a checkpoint callback and export the savedmodel.') + flags.DEFINE_string( + name='tpu', default='', help='TPU address to connect to.') + flags.DEFINE_integer( + name='steps_per_loop', + default=500, + help='Number of steps per training loop. Only training step happens ' + 'inside the loop. Callbacks will not be called inside. Will be capped at ' + 'steps per epoch.') + flags.DEFINE_boolean( + name='use_tf_while_loop', + default=True, + help='Whether to build a tf.while_loop inside the training loop on the ' + 'host. Setting it to True is critical to have peak performance on ' + 'TPU.') + flags.DEFINE_string( + 'optimizer', 'SGD', + 'Name of optimizer preset. (SGD, LARS)') + flags.DEFINE_float( + 'label_smoothing', 0.0, + 'Apply label smoothing to the loss. This applies to ' + 'categorical_cross_entropy; when label_smoothing > 0, ' + 'one-hot encoding is used for the labels.') + flags.DEFINE_integer('eval_offset_epochs', 0, + 'Epoch number of the first evaluation.') + + if model: + flags.DEFINE_string('model', 'resnet50_v1.5', + 'Name of model preset. (mobilenet, resnet50_v1.5)') + if optimizer: + # TODO(kimjaehong): Replace as general hyper-params not only for mobilenet. + flags.DEFINE_float('initial_learning_rate_per_sample', 0.00007, + 'Initial value of learning rate per sample for ' + 'mobilenet_default.') + flags.DEFINE_float('lr_decay_factor', 0.94, + 'Learning rate decay factor for mobilenet_default.') + flags.DEFINE_float('num_epochs_per_decay', 2.5, + 'Number of epochs per decay for mobilenet_default.') + if pretrained_filepath: + flags.DEFINE_string('pretrained_filepath', '', + 'Pretrained file path.') + flags.DEFINE_float('target_accuracy', None, + 'Target eval accuracy, after which training will stop.') + + +def get_synth_data(height, width, num_channels, num_classes, dtype): + """Creates a set of synthetic random data. + + Args: + height: Integer height that will be used to create a fake image tensor. + width: Integer width that will be used to create a fake image tensor. + num_channels: Integer depth that will be used to create a fake image tensor. + num_classes: Number of classes that should be represented in the fake labels + tensor + dtype: Data type for features/images. + + Returns: + A tuple of tensors representing the inputs and labels. + + """ + # Synthetic input should be within [0, 255]. + inputs = tf.random.truncated_normal([height, width, num_channels], + dtype=dtype, + mean=127, + stddev=60, + name='synthetic_inputs') + labels = tf.random.uniform([1], + minval=0, + maxval=num_classes - 1, + dtype=tf.int32, + name='synthetic_labels') + return inputs, labels + + +def define_pruning_flags(): + """Define flags for pruning methods.""" + flags.DEFINE_string('pruning_method', None, + 'Pruning method.' + 'None (no pruning) or polynomial_decay.') + flags.DEFINE_float('pruning_initial_sparsity', 0.0, + 'Initial sparsity for pruning.') + flags.DEFINE_float('pruning_final_sparsity', 0.5, + 'Final sparsity for pruning.') + flags.DEFINE_integer('pruning_begin_step', 0, + 'Begin step for pruning.') + flags.DEFINE_integer('pruning_end_step', 100000, + 'End step for pruning.') + flags.DEFINE_integer('pruning_frequency', 100, + 'Frequency for pruning.') + + +# Map string to TensorFlow dtype +DTYPE_MAP = { + "fp16": tf.float16, + "fp32": tf.float32, + "bf16": tf.bfloat16, +} + + +def get_dl_type(flags_obj): + return DTYPE_MAP[flags_obj.data_loader_image_type] + + +def define_habana_flags(): + """Define HABANA specific flags.""" + flags.DEFINE_enum(name="data_loader_image_type", short_name="dlit", default="fp32", + enum_values=DTYPE_MAP.keys(), + help="data loader images output type") + flags.DEFINE_boolean(name='experimental_preloading', default=False, + help=help_wrap("Support for data.experimental.prefetch_to_device TensorFlow operator." + "This feature is experimental and works only with single node." + "See `-x` switch for `demo_resnet50` script.")) + flags.DEFINE_boolean("use_horovod", default=False, help="Use horovod") + flags.DEFINE_boolean("modeling", default=False, help="Write graph to graph.pbtxt in model dir and export meta graph when enabled.") + + +def get_synth_input_fn(height, width, num_channels, num_classes, + dtype=tf.float32, drop_remainder=True, + experimental_preloading=False): + """Returns an input function that returns a dataset with random data. + + This input_fn returns a data set that iterates over a set of random data and + bypasses all preprocessing, e.g. jpeg decode and copy. The host to device + copy is still included. This used to find the upper throughput bound when + tuning the full input pipeline. + + Args: + height: Integer height that will be used to create a fake image tensor. + width: Integer width that will be used to create a fake image tensor. + num_channels: Integer depth that will be used to create a fake image tensor. + num_classes: Number of classes that should be represented in the fake labels + tensor + dtype: Data type for features/images. + drop_remainder: A boolean indicates whether to drop the remainder of the + batches. If True, the batch dimension will be static. + + Returns: + An input_fn that can be used in place of a real one to return a dataset + that can be used for iteration. + """ + # pylint: disable=unused-argument + def input_fn(is_training, data_dir, batch_size, *args, **kwargs): + """Returns dataset filled with random data.""" + inputs, labels = get_synth_data(height=height, + width=width, + num_channels=num_channels, + num_classes=num_classes, + dtype=dtype) + # Cast to float32 for Keras model. + labels = tf.cast(labels, dtype=tf.float32) + data = tf.data.Dataset.from_tensors((inputs, labels)).repeat() + + # `drop_remainder` will make dataset produce outputs with known shapes. + data = data.batch(batch_size, drop_remainder=drop_remainder) + if experimental_preloading: + device = "/device:HPU:0" + with tf.device(device): + data = data.apply(tf.data.experimental.prefetch_to_device(device)) + else: + data = data.prefetch(buffer_size=tf.data.experimental.AUTOTUNE) + return data + + return input_fn + + +def set_cudnn_batchnorm_mode(): + """Set CuDNN batchnorm mode for better performance. + + Note: Spatial Persistent mode may lead to accuracy losses for certain + models. + """ + if FLAGS.batchnorm_spatial_persistent: + os.environ['TF_USE_CUDNN_BATCHNORM_SPATIAL_PERSISTENT'] = '1' + else: + os.environ.pop('TF_USE_CUDNN_BATCHNORM_SPATIAL_PERSISTENT', None) diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/mlp_log.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/mlp_log.py new file mode 100644 index 0000000000000000000000000000000000000000..2b1f4b3a8a0c2ce8e47a4c630d017d84dd57bcf5 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/mlp_log.py @@ -0,0 +1,57 @@ +# 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. +# ============================================================================== +"""Convenience function for logging compliance tags to stdout. +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + + +import inspect +import json +import logging +import os +import re +import sys +import time + +try: + import horovod.tensorflow as hvd +except ImportError: + hvd = None + +def get_mllog_mlloger(output_dir=None): + from mlperf_logging import mllog + + if hvd is not None and hvd.is_initialized(): + str_hvd_rank = str(hvd.rank()) + else: + str_hvd_rank = "0" + mllogger = mllog.get_mllogger() + mllogger.propagate = False + mllog.propagate=False + if output_dir is None: output_dir='./log' + filenames = os.path.normpath(output_dir) + "/result_rank_" + str_hvd_rank + ".txt" + mllog.config(filename=filenames) + workername = "worker" + str_hvd_rank + mllog.config( + default_namespace = workername, + default_stack_offset = 1, + default_clear_line = False, + root_dir = os.path.normpath( + os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", ".."))) + + return mllogger, mllog diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/mlperf_variable_map.json b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/mlperf_variable_map.json new file mode 100644 index 0000000000000000000000000000000000000000..f439d8c1989adf431c29031ba63b1df37ab8c90f --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/mlperf_variable_map.json @@ -0,0 +1,163 @@ +{ + "conv1/kernel": "conv0_weight", + "bn_conv1/gamma": "bn0_gamma", + "bn_conv1/beta": "bn0_beta", + "res2a_branch2a/kernel": "stage1_unit1_conv1_weight", + "bn2a_branch2a/gamma": "stage1_unit1_bn1_gamma", + "bn2a_branch2a/beta": "stage1_unit1_bn1_beta", + "res2a_branch2b/kernel": "stage1_unit1_conv2_weight", + "bn2a_branch2b/gamma": "stage1_unit1_bn2_gamma", + "bn2a_branch2b/beta": "stage1_unit1_bn2_beta", + "res2a_branch2c/kernel": "stage1_unit1_conv3_weight", + "bn2a_branch2c/gamma": "stage1_unit1_bn3_gamma", + "bn2a_branch2c/beta": "stage1_unit1_bn3_beta", + "res2a_branch1/kernel": "stage1_unit1_conv1sc_weight", + "bn2a_branch1/gamma": "stage1_unit1_bnsc_gamma", + "bn2a_branch1/beta": "stage1_unit1_bnsc_beta", + "res2b_branch2a/kernel": "stage1_unit2_conv1_weight", + "bn2b_branch2a/gamma": "stage1_unit2_bn1_gamma", + "bn2b_branch2a/beta": "stage1_unit2_bn1_beta", + "res2b_branch2b/kernel": "stage1_unit2_conv2_weight", + "bn2b_branch2b/gamma": "stage1_unit2_bn2_gamma", + "bn2b_branch2b/beta": "stage1_unit2_bn2_beta", + "res2b_branch2c/kernel": "stage1_unit2_conv3_weight", + "bn2b_branch2c/gamma": "stage1_unit2_bn3_gamma", + "bn2b_branch2c/beta": "stage1_unit2_bn3_beta", + "res2c_branch2a/kernel": "stage1_unit3_conv1_weight", + "bn2c_branch2a/gamma": "stage1_unit3_bn1_gamma", + "bn2c_branch2a/beta": "stage1_unit3_bn1_beta", + "res2c_branch2b/kernel": "stage1_unit3_conv2_weight", + "bn2c_branch2b/gamma": "stage1_unit3_bn2_gamma", + "bn2c_branch2b/beta": "stage1_unit3_bn2_beta", + "res2c_branch2c/kernel": "stage1_unit3_conv3_weight", + "bn2c_branch2c/gamma": "stage1_unit3_bn3_gamma", + "bn2c_branch2c/beta": "stage1_unit3_bn3_beta", + "res3a_branch2a/kernel": "stage2_unit1_conv1_weight", + "bn3a_branch2a/gamma": "stage2_unit1_bn1_gamma", + "bn3a_branch2a/beta": "stage2_unit1_bn1_beta", + "res3a_branch2b/kernel": "stage2_unit1_conv2_weight", + "bn3a_branch2b/gamma": "stage2_unit1_bn2_gamma", + "bn3a_branch2b/beta": "stage2_unit1_bn2_beta", + "res3a_branch2c/kernel": "stage2_unit1_conv3_weight", + "bn3a_branch2c/gamma": "stage2_unit1_bn3_gamma", + "bn3a_branch2c/beta": "stage2_unit1_bn3_beta", + "res3a_branch1/kernel": "stage2_unit1_conv1sc_weight", + "bn3a_branch1/gamma": "stage2_unit1_bnsc_gamma", + "bn3a_branch1/beta": "stage2_unit1_bnsc_beta", + "res3b_branch2a/kernel": "stage2_unit2_conv1_weight", + "bn3b_branch2a/gamma": "stage2_unit2_bn1_gamma", + "bn3b_branch2a/beta": "stage2_unit2_bn1_beta", + "res3b_branch2b/kernel": "stage2_unit2_conv2_weight", + "bn3b_branch2b/gamma": "stage2_unit2_bn2_gamma", + "bn3b_branch2b/beta": "stage2_unit2_bn2_beta", + "res3b_branch2c/kernel": "stage2_unit2_conv3_weight", + "bn3b_branch2c/gamma": "stage2_unit2_bn3_gamma", + "bn3b_branch2c/beta": "stage2_unit2_bn3_beta", + "res3c_branch2a/kernel": "stage2_unit3_conv1_weight", + "bn3c_branch2a/gamma": "stage2_unit3_bn1_gamma", + "bn3c_branch2a/beta": "stage2_unit3_bn1_beta", + "res3c_branch2b/kernel": "stage2_unit3_conv2_weight", + "bn3c_branch2b/gamma": "stage2_unit3_bn2_gamma", + "bn3c_branch2b/beta": "stage2_unit3_bn2_beta", + "res3c_branch2c/kernel": "stage2_unit3_conv3_weight", + "bn3c_branch2c/gamma": "stage2_unit3_bn3_gamma", + "bn3c_branch2c/beta": "stage2_unit3_bn3_beta", + "res3d_branch2a/kernel": "stage2_unit4_conv1_weight", + "bn3d_branch2a/gamma": "stage2_unit4_bn1_gamma", + "bn3d_branch2a/beta": "stage2_unit4_bn1_beta", + "res3d_branch2b/kernel": "stage2_unit4_conv2_weight", + "bn3d_branch2b/gamma": "stage2_unit4_bn2_gamma", + "bn3d_branch2b/beta": "stage2_unit4_bn2_beta", + "res3d_branch2c/kernel": "stage2_unit4_conv3_weight", + "bn3d_branch2c/gamma": "stage2_unit4_bn3_gamma", + "bn3d_branch2c/beta": "stage2_unit4_bn3_beta", + "res4a_branch2a/kernel": "stage3_unit1_conv1_weight", + "bn4a_branch2a/gamma": "stage3_unit1_bn1_gamma", + "bn4a_branch2a/beta": "stage3_unit1_bn1_beta", + "res4a_branch2b/kernel": "stage3_unit1_conv2_weight", + "bn4a_branch2b/gamma": "stage3_unit1_bn2_gamma", + "bn4a_branch2b/beta": "stage3_unit1_bn2_beta", + "res4a_branch2c/kernel": "stage3_unit1_conv3_weight", + "bn4a_branch2c/gamma": "stage3_unit1_bn3_gamma", + "bn4a_branch2c/beta": "stage3_unit1_bn3_beta", + "res4a_branch1/kernel": "stage3_unit1_conv1sc_weight", + "bn4a_branch1/gamma": "stage3_unit1_bnsc_gamma", + "bn4a_branch1/beta": "stage3_unit1_bnsc_beta", + "res4b_branch2a/kernel": "stage3_unit2_conv1_weight", + "bn4b_branch2a/gamma": "stage3_unit2_bn1_gamma", + "bn4b_branch2a/beta": "stage3_unit2_bn1_beta", + "res4b_branch2b/kernel": "stage3_unit2_conv2_weight", + "bn4b_branch2b/gamma": "stage3_unit2_bn2_gamma", + "bn4b_branch2b/beta": "stage3_unit2_bn2_beta", + "res4b_branch2c/kernel": "stage3_unit2_conv3_weight", + "bn4b_branch2c/gamma": "stage3_unit2_bn3_gamma", + "bn4b_branch2c/beta": "stage3_unit2_bn3_beta", + "res4c_branch2a/kernel": "stage3_unit3_conv1_weight", + "bn4c_branch2a/gamma": "stage3_unit3_bn1_gamma", + "bn4c_branch2a/beta": "stage3_unit3_bn1_beta", + "res4c_branch2b/kernel": "stage3_unit3_conv2_weight", + "bn4c_branch2b/gamma": "stage3_unit3_bn2_gamma", + "bn4c_branch2b/beta": "stage3_unit3_bn2_beta", + "res4c_branch2c/kernel": "stage3_unit3_conv3_weight", + "bn4c_branch2c/gamma": "stage3_unit3_bn3_gamma", + "bn4c_branch2c/beta": "stage3_unit3_bn3_beta", + "res4d_branch2a/kernel": "stage3_unit4_conv1_weight", + "bn4d_branch2a/gamma": "stage3_unit4_bn1_gamma", + "bn4d_branch2a/beta": "stage3_unit4_bn1_beta", + "res4d_branch2b/kernel": "stage3_unit4_conv2_weight", + "bn4d_branch2b/gamma": "stage3_unit4_bn2_gamma", + "bn4d_branch2b/beta": "stage3_unit4_bn2_beta", + "res4d_branch2c/kernel": "stage3_unit4_conv3_weight", + "bn4d_branch2c/gamma": "stage3_unit4_bn3_gamma", + "bn4d_branch2c/beta": "stage3_unit4_bn3_beta", + "res4e_branch2a/kernel": "stage3_unit5_conv1_weight", + "bn4e_branch2a/gamma": "stage3_unit5_bn1_gamma", + "bn4e_branch2a/beta": "stage3_unit5_bn1_beta", + "res4e_branch2b/kernel": "stage3_unit5_conv2_weight", + "bn4e_branch2b/gamma": "stage3_unit5_bn2_gamma", + "bn4e_branch2b/beta": "stage3_unit5_bn2_beta", + "res4e_branch2c/kernel": "stage3_unit5_conv3_weight", + "bn4e_branch2c/gamma": "stage3_unit5_bn3_gamma", + "bn4e_branch2c/beta": "stage3_unit5_bn3_beta", + "res4f_branch2a/kernel": "stage3_unit6_conv1_weight", + "bn4f_branch2a/gamma": "stage3_unit6_bn1_gamma", + "bn4f_branch2a/beta": "stage3_unit6_bn1_beta", + "res4f_branch2b/kernel": "stage3_unit6_conv2_weight", + "bn4f_branch2b/gamma": "stage3_unit6_bn2_gamma", + "bn4f_branch2b/beta": "stage3_unit6_bn2_beta", + "res4f_branch2c/kernel": "stage3_unit6_conv3_weight", + "bn4f_branch2c/gamma": "stage3_unit6_bn3_gamma", + "bn4f_branch2c/beta": "stage3_unit6_bn3_beta", + "res5a_branch2a/kernel": "stage4_unit1_conv1_weight", + "bn5a_branch2a/gamma": "stage4_unit1_bn1_gamma", + "bn5a_branch2a/beta": "stage4_unit1_bn1_beta", + "res5a_branch2b/kernel": "stage4_unit1_conv2_weight", + "bn5a_branch2b/gamma": "stage4_unit1_bn2_gamma", + "bn5a_branch2b/beta": "stage4_unit1_bn2_beta", + "res5a_branch2c/kernel": "stage4_unit1_conv3_weight", + "bn5a_branch2c/gamma": "stage4_unit1_bn3_gamma", + "bn5a_branch2c/beta": "stage4_unit1_bn3_beta", + "res5a_branch1/kernel": "stage4_unit1_conv1sc_weight", + "bn5a_branch1/gamma": "stage4_unit1_bnsc_gamma", + "bn5a_branch1/beta": "stage4_unit1_bnsc_beta", + "res5b_branch2a/kernel": "stage4_unit2_conv1_weight", + "bn5b_branch2a/gamma": "stage4_unit2_bn1_gamma", + "bn5b_branch2a/beta": "stage4_unit2_bn1_beta", + "res5b_branch2b/kernel": "stage4_unit2_conv2_weight", + "bn5b_branch2b/gamma": "stage4_unit2_bn2_gamma", + "bn5b_branch2b/beta": "stage4_unit2_bn2_beta", + "res5b_branch2c/kernel": "stage4_unit2_conv3_weight", + "bn5b_branch2c/gamma": "stage4_unit2_bn3_gamma", + "bn5b_branch2c/beta": "stage4_unit2_bn3_beta", + "res5c_branch2a/kernel": "stage4_unit3_conv1_weight", + "bn5c_branch2a/gamma": "stage4_unit3_bn1_gamma", + "bn5c_branch2a/beta": "stage4_unit3_bn1_beta", + "res5c_branch2b/kernel": "stage4_unit3_conv2_weight", + "bn5c_branch2b/gamma": "stage4_unit3_bn2_gamma", + "bn5c_branch2b/beta": "stage4_unit3_bn2_beta", + "res5c_branch2c/kernel": "stage4_unit3_conv3_weight", + "bn5c_branch2c/gamma": "stage4_unit3_bn3_gamma", + "bn5c_branch2c/beta": "stage4_unit3_bn3_beta", + "fc1000/kernel": "fc1_weight", + "fc1000/bias": "fc1_bias" + } \ No newline at end of file diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/requirements.txt b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..0c76087cd3f97fae099c27a4083a1b04151a3afe --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/requirements.txt @@ -0,0 +1,7 @@ +absl_py==1.0.0 +cloudpickle==1.6.0 +psutil==5.8.0 +PyYAML==6.0.0 +requests==2.25.1 +tensorflow_model_optimization==0.7.2 +git+https://github.com/mlperf/logging.git@1.0.0 diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/resnet_ctl_imagenet_main.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/resnet_ctl_imagenet_main.py new file mode 100644 index 0000000000000000000000000000000000000000..d28aaaa5a08258f2788d382ff28e0036bdf11d47 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/resnet_ctl_imagenet_main.py @@ -0,0 +1,406 @@ +# Copyright 2019 The TensorFlow Authors. 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. +# ============================================================================== +# List of changes: +# - loading habana module +# - added support for prefetching to HPU +# - added profiling callbacks support +# - changed include paths of modules +# - include mechanism for dumping tensors + +# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company + +"""Runs a ResNet model on the ImageNet dataset using custom training loops.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +import shutil + +from absl import app +from absl import flags +from absl import logging +import tensorflow as tf +import os +import math + +from TensorFlow.common.modeling import performance +from TensorFlow.common.training import controller +from TensorFlow.utils.flags import core as flags_core +from TensorFlow.utils.logs import logger +from TensorFlow.utils.misc import distribution_utils +from TensorFlow.utils.misc import keras_utils +from TensorFlow.utils.misc import model_helpers +from TensorFlow.computer_vision.common import imagenet_preprocessing +from TensorFlow.computer_vision.Resnets.utils.optimizers.keras import lars_util +from TensorFlow.computer_vision.Resnets.resnet_keras import common +from TensorFlow.computer_vision.Resnets.resnet_keras import resnet_runnable +from TensorFlow.computer_vision.Resnets.resnet_keras.common import get_global_batch_size +from habana_frameworks.tensorflow import load_habana_module +from TensorFlow.common.debug import dump_callback +from TensorFlow.common.tb_utils import write_hparams_v2 +from habana_frameworks.tensorflow.synapse_logger_helpers import synapse_logger_init +from TensorFlow.computer_vision.Resnets.resnet_keras.mlp_log import get_mllog_mlloger + +try: + import horovod.tensorflow as hvd +except ImportError as e: + _hvd_exc = e + hvd = None + +flags.DEFINE_boolean(name='use_tf_function', default=True, + help='Wrap the train and test step inside a ' + 'tf.function.') +flags.DEFINE_boolean(name='single_l2_loss_op', default=False, + help='Calculate L2_loss on concatenated weights, ' + 'instead of using Keras per-layer L2 loss.') +flags.DEFINE_boolean(name='cache_decoded_image', + default=False, + help='Whether or not to cache decoded images in the ' + 'input pipeline. If this flag and `cache` is enabled, ' + 'then TFExample protos will be parsed and then cached ' + 'which reduces the load on hosts.') +flags.DEFINE_boolean(name='dist_eval', default=True, + help='Partial eval in each rank and allreduce the partial result') +flags.DEFINE_boolean(name='enable_device_warmup', + default=False, + help='Whether or not to enable device warmup. This ' + 'includes training on dummy data and enabling graph/XLA ' + 'compilation before run_start.') +flags.DEFINE_integer(name='device_warmup_steps', + default=2, + help='The number of steps to apply for device warmup.') +flags.DEFINE_float('base_learning_rate', 0.1, + 'Base learning rate. ' + 'This is the learning rate when using batch size 256; when using other ' + 'batch sizes, the learning rate will be scaled linearly.') +flags.DEFINE_boolean(name='profile', default=False, + help='Running RN50 with profiling') +flags.DEFINE_integer(name='num_train_files', + default=1024, + help='The number of training tf records.') +flags.DEFINE_integer(name='num_eval_files', + default=128, + help='The number of evaluation tf records.') +flags.DEFINE_integer(name='num_acc_steps', default=1, help='Number of gradient accumulation steps.') + + +def build_stats(runnable, time_callback): + """Normalizes and returns dictionary of stats. + + Args: + runnable: The module containing all the training and evaluation metrics. + time_callback: Time tracking callback instance. + + Returns: + Dictionary of normalized results. + """ + stats = {} + + if not runnable.flags_obj.skip_eval: + if runnable.test_loss: + stats['eval_loss'] = runnable.test_loss.result().numpy() + if runnable.test_accuracy: + stats['eval_acc'] = runnable.eval_accuracy + + if runnable.train_loss: + stats['train_loss'] = runnable.train_loss.result().numpy() + if runnable.train_accuracy: + stats['train_acc'] = runnable.train_accuracy.result().numpy() + + if time_callback: + timestamp_log = time_callback.timestamp_log + stats['step_timestamp_log'] = timestamp_log + stats['train_finish_time'] = time_callback.train_finish_time + if time_callback.epoch_runtime_log: + stats['avg_exp_per_second'] = time_callback.average_examples_per_second + + return stats + + +def get_num_train_iterations(flags_obj): + """Returns the number of training steps, train and test epochs.""" + global_batch_size = get_global_batch_size(flags_obj.batch_size, flags_obj.num_acc_steps) + steps_per_epoch = math.ceil(imagenet_preprocessing.NUM_IMAGES['train'] / global_batch_size) + train_epochs = flags_obj.train_epochs + + if train_epochs == 0 and flags_obj.train_steps > 0: + steps_per_epoch = flags_obj.train_steps + train_epochs = 1 + + eval_batch_size = flags_obj.batch_size + if flags_obj.dist_eval: + eval_batch_size = global_batch_size + eval_steps = ( + math.ceil(imagenet_preprocessing.NUM_IMAGES['validation'] / eval_batch_size)) + + return steps_per_epoch, train_epochs, eval_steps + + +def _steps_to_run(steps_in_current_epoch, steps_per_epoch, steps_per_loop): + """Calculates steps to run on device.""" + if steps_per_loop <= 0: + raise ValueError('steps_per_loop should be positive integer.') + if steps_per_loop == 1: + return steps_per_loop + return min(steps_per_loop, steps_per_epoch - steps_in_current_epoch) + + +def run(flags_obj): + """Run ResNet ImageNet training and eval loop using custom training loops. + + Args: + flags_obj: An object containing parsed flag values. + + Raises: + ValueError: If fp16 is passed as it is not currently supported. + + Returns: + Dictionary of training and eval stats. + """ + tf.get_logger().propagate = False + output_dir = None + if "LOG_DIR" in os.environ: + output_dir = os.environ["LOG_DIR"] + mlperf_mlloger, mlperf_mllog = get_mllog_mlloger(output_dir) + mlperf_mlloger.event(key=mlperf_mllog.constants.CACHE_CLEAR, value=True) + mlperf_mlloger.start(key=mlperf_mllog.constants.INIT_START, value=None) + mlperf_mlloger.event(key=mlperf_mllog.constants.SUBMISSION_BENCHMARK, value=mlperf_mllog.constants.RESNET) + mlperf_mlloger.event(key=mlperf_mllog.constants.SUBMISSION_ORG, value='Habana') + mlperf_mlloger.event(key=mlperf_mllog.constants.SUBMISSION_DIVISION, value='closed') + mlperf_mlloger.event(key=mlperf_mllog.constants.SUBMISSION_PLATFORM, value='gaudi-{}'.format(flags_obj.num_gpus)) + mlperf_mlloger.event(key=mlperf_mllog.constants.SUBMISSION_STATUS, value='onprem') + + keras_utils.set_session_config( + enable_eager=flags_obj.enable_eager, + enable_xla=flags_obj.enable_xla) + performance.set_mixed_precision_policy(flags_core.get_tf_dtype(flags_obj)) + + # This only affects GPU. + common.set_cudnn_batchnorm_mode() + + # TODO(anj-s): Set data_format without using Keras. + data_format = flags_obj.data_format + if data_format is None: + data_format = ('channels_first' + if tf.test.is_built_with_cuda() else 'channels_last') + tf.keras.backend.set_image_data_format(data_format) + + if hvd is not None and hvd.is_initialized(): + model_dir = os.path.join( + flags_obj.model_dir, "worker_" + str(hvd.rank())) + else: + model_dir = flags_obj.model_dir + + global_batch_size = get_global_batch_size(flags_obj.batch_size, flags_obj.num_acc_steps) + + strategy = distribution_utils.get_distribution_strategy( + distribution_strategy=flags_obj.distribution_strategy, + num_gpus=flags_obj.num_gpus, + all_reduce_alg=flags_obj.all_reduce_alg, + num_packs=flags_obj.num_packs, + tpu_address=flags_obj.tpu) + + mlperf_mlloger.event(key=mlperf_mllog.constants.GLOBAL_BATCH_SIZE, value=global_batch_size) + mlperf_mlloger.event(key=mlperf_mllog.constants.TRAIN_SAMPLES, value=imagenet_preprocessing.NUM_IMAGES['train']) + mlperf_mlloger.event(key=mlperf_mllog.constants.EVAL_SAMPLES, value=imagenet_preprocessing.NUM_IMAGES['validation']) + group_batch_norm = 1 + mlperf_mlloger.event(key=mlperf_mllog.constants.MODEL_BN_SPAN, value= flags_obj.batch_size * group_batch_norm) + mlperf_mlloger.event(key=mlperf_mllog.constants.GRADIENT_ACCUMULATION_STEPS, value= flags_obj.num_acc_steps) + + train_writer, eval_writer = None, None + if flags_obj.enable_tensorboard: + train_writer = tf.summary.create_file_writer(model_dir) + eval_writer = tf.summary.create_file_writer(os.path.join(model_dir, 'eval')) + hparams = flags_obj.flag_values_dict() + write_hparams_v2(train_writer, hparams) + + per_epoch_steps, train_epochs, eval_steps = get_num_train_iterations( + flags_obj) + steps_per_loop = min(flags_obj.steps_per_loop, per_epoch_steps) + train_steps = train_epochs * per_epoch_steps + + logging.info( + 'Training %d epochs, each epoch has %d steps, ' + 'total steps: %d; Eval %d steps', train_epochs, per_epoch_steps, + train_steps, eval_steps) + + time_callback = keras_utils.TimeHistory( + global_batch_size, + flags_obj.log_steps, + summary_writer=train_writer, + batch_size_per_node=flags_obj.batch_size) + profiler_callback = None + if flags_obj.profile_steps is not None: + profiler_callback = keras_utils.get_profiler_callback( + model_dir, + flags_obj.profile_steps, + flags_obj.enable_tensorboard, + per_epoch_steps) + with distribution_utils.get_strategy_scope(strategy): + runnable = resnet_runnable.ResnetRunnable(flags_obj, time_callback, + train_steps, + per_epoch_steps, + profiler_callback,mlperf_mlloger,mlperf_mllog) + + eval_interval = flags_obj.epochs_between_evals * per_epoch_steps + eval_offset = flags_obj.eval_offset_epochs * per_epoch_steps + if eval_offset != 0: + eval_offset -= eval_interval + checkpoint_interval = ( + per_epoch_steps if flags_obj.enable_checkpoint_and_export else None) + summary_interval = per_epoch_steps if flags_obj.enable_tensorboard else None + + checkpoint_manager = tf.train.CheckpointManager( + runnable.checkpoint, + directory=model_dir, + max_to_keep=10, + step_counter=runnable.global_step, + checkpoint_interval=checkpoint_interval) + + device_warmup_steps = ( + flags_obj.device_warmup_steps if flags_obj.enable_device_warmup else 0) + + if flags_obj.enable_device_warmup: + logging.info('Warmup for %d steps.', device_warmup_steps) + + train_steps=per_epoch_steps * train_epochs + + resnet_controller = controller.Controller( + strategy, + runnable.train, + runnable.evaluate, + runnable.warmup, + global_step=runnable.global_step, + steps_per_loop=steps_per_loop, + train_steps=train_steps, + checkpoint_manager=checkpoint_manager, + summary_interval=summary_interval, + eval_steps=eval_steps, + eval_interval=eval_interval, + eval_offset=eval_offset, + device_warmup_steps=device_warmup_steps, + train_summary_writer=train_writer, + eval_summary_writer=eval_writer) + + if flags_obj.enable_device_warmup: + resnet_controller.warmup() + del runnable.warmup_train_iter + del runnable.warmup_train_dataset + del runnable.warmup_eval_iter + del runnable.warmup_eval_dataset + try: + synth_data_dir = f'{model_dir}/resnet_synth_data' + shutil.rmtree(synth_data_dir) + except: + pass + + manifest_path = prepare_dataset_manifest(flags_obj) + + mlperf_mlloger.end(key=mlperf_mllog.constants.INIT_STOP) + + if flags.FLAGS.use_horovod: + hvd.broadcast(0, 0) + time_callback.on_train_begin() + mlperf_mlloger.start(key=mlperf_mllog.constants.RUN_START) + mlperf_mlloger.start( + key=mlperf_mllog.constants.BLOCK_START, value=None, + metadata={ + 'first_epoch_num': 1, + 'epoch_count': + (flags_obj.eval_offset_epochs if flags_obj.eval_offset_epochs > 0 + else flags_obj.epochs_between_evals) + }) + resnet_controller.train(evaluate=not flags_obj.skip_eval, num_acc_steps=flags_obj.num_acc_steps, manifest_path=manifest_path) + if not flags_obj.skip_eval: + eval_accuracy = resnet_controller.last_eval_output['test_accuracy'] + if eval_accuracy >= flags_obj.target_accuracy: + mlperf_mlloger.end(key=mlperf_mllog.constants.RUN_STOP, value=None, metadata={'status': 'success'}) + else: + mlperf_mlloger.end(key=mlperf_mllog.constants.RUN_STOP, value=None, metadata={'status': 'fail'}) + time_callback.on_train_end() + + + stats = build_stats(runnable, time_callback) + return stats + + +def prepare_dataset_manifest(flags_obj): + import glob + import json + import pathlib + + from habana_frameworks.tensorflow.multinode_helpers import comm_rank + + manifest_file_name = f"imagenet_jpeg_manifest_rank_{comm_rank()}.json" + manifest_path = os.path.join('/tmp', manifest_file_name) + + if flags_obj.jpeg_data_dir is not None: + # get files list + dataset_dir = os.path.join(flags_obj.jpeg_data_dir, 'train') + + print(f"dataset dir: {dataset_dir}") + manifest_data = {} + manifest_data["file_list"] = sorted( + glob.glob(dataset_dir + "/*/*.{}".format("JPEG"))) + + # get class list + data_dir = pathlib.Path(dataset_dir) + manifest_data["class_list"] = sorted( + [item.name for item in data_dir.glob('*') if item.is_dir() == True]) + + file_sizes = {} + file_classes = [] + + for filename in manifest_data["file_list"]: + #Everything is in order as file_list is sorted + file_sizes[filename] = os.stat(filename).st_size + file_classes.append(os.path.basename(os.path.dirname(filename))) + + manifest_data['file_sizes'] = file_sizes + manifest_data['file_classes'] = file_classes + + with open(manifest_path, "w") as f: + json.dump(manifest_data, f) + + return manifest_path + + +def main(_): + if flags.FLAGS.use_horovod: + if hvd is None: + logging.error("Problem encountered during Horovod import. Please make sure that habana-horovod package is installed.") + raise _hvd_exc + hvd.init() + else: + synapse_logger_init() + + os.environ['TF_EXPERIMENTAL_BATCH_VARIABLES'] = '1' + os.environ['TF_CLUSTER_VARIABLES'] = '1' + load_habana_module() + + with dump_callback(): + model_helpers.apply_clean(flags.FLAGS) + with logger.benchmark_context(flags.FLAGS): + stats =run (flags.FLAGS) + logging.info('Run stats:\n%s', stats) + + +if __name__ == '__main__': + logging.set_verbosity(logging.INFO) + common.define_keras_flags() + common.define_habana_flags() + lars_util.define_lars_flags() + app.run(main) + diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/resnet_model.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/resnet_model.py new file mode 100644 index 0000000000000000000000000000000000000000..21351b8f0e03abba1b12ca38786baa221626735e --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/resnet_model.py @@ -0,0 +1,323 @@ +# Copyright 2021 The TensorFlow Authors. 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. + +"""ResNet50 model for Keras. +Adapted from tf.keras.applications.resnet50.ResNet50(). +This is ResNet model version 1.5. +Related papers/blogs: +- https://arxiv.org/abs/1512.03385 +- https://arxiv.org/pdf/1603.05027v2.pdf +- http://torch.ch/blog/2016/02/04/resnets.html +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from absl import flags +import tensorflow as tf +from TensorFlow.computer_vision.common import imagenet_preprocessing + +FLAGS = flags.FLAGS +flags.DEFINE_float( + 'weight_decay', + default=1e-4, + help=('Weight decay coefficiant for l2 regularization.')) + +layers = tf.keras.layers + + +def _gen_l2_regularizer(use_l2_regularizer=True): + return tf.keras.regularizers.L2( + FLAGS.weight_decay) if use_l2_regularizer else None + + +def identity_block(input_tensor, + kernel_size, + filters, + stage, + block, + use_l2_regularizer=True, + batch_norm_decay=0.9, + batch_norm_epsilon=1e-5): + """The identity block is the block that has no conv layer at shortcut. + Args: + input_tensor: input tensor + kernel_size: default 3, the kernel size of middle conv layer at main path + filters: list of integers, the filters of 3 conv layer at main path + stage: integer, current stage label, used for generating layer names + block: 'a','b'..., current block label, used for generating layer names + use_l2_regularizer: whether to use L2 regularizer on Conv layer. + batch_norm_decay: Moment of batch norm layers. + batch_norm_epsilon: Epsilon of batch borm layers. + Returns: + Output tensor for the block. + """ + filters1, filters2, filters3 = filters + if tf.keras.backend.image_data_format() == 'channels_last': + bn_axis = 3 + else: + bn_axis = 1 + conv_name_base = 'res' + str(stage) + block + '_branch' + bn_name_base = 'bn' + str(stage) + block + '_branch' + + x = layers.Conv2D( + filters1, (1, 1), + use_bias=False, + kernel_initializer='he_normal', + kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), + name=conv_name_base + '2a')( + input_tensor) + x = layers.BatchNormalization( + axis=bn_axis, + momentum=batch_norm_decay, + epsilon=batch_norm_epsilon, + name=bn_name_base + '2a')( + x) + x = layers.Activation('relu')(x) + + x = layers.Conv2D( + filters2, + kernel_size, + padding='same', + use_bias=False, + kernel_initializer='he_normal', + kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), + name=conv_name_base + '2b')( + x) + x = layers.BatchNormalization( + axis=bn_axis, + momentum=batch_norm_decay, + epsilon=batch_norm_epsilon, + name=bn_name_base + '2b')( + x) + x = layers.Activation('relu')(x) + + x = layers.Conv2D( + filters3, (1, 1), + use_bias=False, + kernel_initializer='he_normal', + kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), + name=conv_name_base + '2c')( + x) + x = layers.BatchNormalization( + axis=bn_axis, + momentum=batch_norm_decay, + epsilon=batch_norm_epsilon, + name=bn_name_base + '2c')( + x) + + x = layers.add([x, input_tensor]) + x = layers.Activation('relu')(x) + return x + + +def conv_block(input_tensor, + kernel_size, + filters, + stage, + block, + strides=(2, 2), + use_l2_regularizer=True, + batch_norm_decay=0.9, + batch_norm_epsilon=1e-5): + """A block that has a conv layer at shortcut. + Note that from stage 3, + the second conv layer at main path is with strides=(2, 2) + And the shortcut should have strides=(2, 2) as well + Args: + input_tensor: input tensor + kernel_size: default 3, the kernel size of middle conv layer at main path + filters: list of integers, the filters of 3 conv layer at main path + stage: integer, current stage label, used for generating layer names + block: 'a','b'..., current block label, used for generating layer names + strides: Strides for the second conv layer in the block. + use_l2_regularizer: whether to use L2 regularizer on Conv layer. + batch_norm_decay: Moment of batch norm layers. + batch_norm_epsilon: Epsilon of batch borm layers. + Returns: + Output tensor for the block. + """ + filters1, filters2, filters3 = filters + if tf.keras.backend.image_data_format() == 'channels_last': + bn_axis = 3 + else: + bn_axis = 1 + conv_name_base = 'res' + str(stage) + block + '_branch' + bn_name_base = 'bn' + str(stage) + block + '_branch' + + x = layers.Conv2D( + filters1, (1, 1), + use_bias=False, + kernel_initializer='he_normal', + kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), + name=conv_name_base + '2a')( + input_tensor) + x = layers.BatchNormalization( + axis=bn_axis, + momentum=batch_norm_decay, + epsilon=batch_norm_epsilon, + name=bn_name_base + '2a')( + x) + x = layers.Activation('relu')(x) + + x = layers.Conv2D( + filters2, + kernel_size, + strides=strides, + padding='same', + use_bias=False, + kernel_initializer='he_normal', + kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), + name=conv_name_base + '2b')( + x) + x = layers.BatchNormalization( + axis=bn_axis, + momentum=batch_norm_decay, + epsilon=batch_norm_epsilon, + name=bn_name_base + '2b')( + x) + x = layers.Activation('relu')(x) + + x = layers.Conv2D( + filters3, (1, 1), + use_bias=False, + kernel_initializer='he_normal', + kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), + name=conv_name_base + '2c')( + x) + x = layers.BatchNormalization( + axis=bn_axis, + momentum=batch_norm_decay, + epsilon=batch_norm_epsilon, + name=bn_name_base + '2c')( + x) + + shortcut = layers.Conv2D( + filters3, (1, 1), + strides=strides, + use_bias=False, + kernel_initializer='he_normal', + kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), + name=conv_name_base + '1')( + input_tensor) + shortcut = layers.BatchNormalization( + axis=bn_axis, + momentum=batch_norm_decay, + epsilon=batch_norm_epsilon, + name=bn_name_base + '1')( + shortcut) + + x = layers.add([x, shortcut]) + x = layers.Activation('relu')(x) + return x + + +def resnet50(num_classes, + batch_size=None, + use_l2_regularizer=True, + rescale_inputs=False, + batch_norm_decay=0.9, + batch_norm_epsilon=1e-5): + """Instantiates the ResNet50 architecture. + Args: + num_classes: `int` number of classes for image classification. + batch_size: Size of the batches for each step. + use_l2_regularizer: whether to use L2 regularizer on Conv/Dense layer. + rescale_inputs: whether to rescale inputs from 0 to 1. + batch_norm_decay: Moment of batch norm layers. + batch_norm_epsilon: Epsilon of batch borm layers. + Returns: + A Keras model instance. + """ + input_shape = (224, 224, 3) + img_input = layers.Input(shape=input_shape, batch_size=batch_size) + if rescale_inputs: + # Hub image modules expect inputs in the range [0, 1]. This rescales these + # inputs to the range expected by the trained model. + x = layers.Lambda( + lambda x: x * 255.0 - tf.keras.backend.constant( # pylint: disable=g-long-lambda + imagenet_preprocessing.CHANNEL_MEANS, + shape=[1, 1, 3], + dtype=x.dtype), + name='rescale')( + img_input) + else: + x = img_input + + if tf.keras.backend.image_data_format() == 'channels_first': + x = layers.Permute((3, 1, 2))(x) + bn_axis = 1 + else: # channels_last + bn_axis = 3 + + block_config = dict( + use_l2_regularizer=use_l2_regularizer, + batch_norm_decay=batch_norm_decay, + batch_norm_epsilon=batch_norm_epsilon) + x = layers.ZeroPadding2D(padding=(3, 3), name='conv1_pad')(x) + x = layers.Conv2D( + 64, (7, 7), + strides=(2, 2), + padding='valid', + use_bias=False, + kernel_initializer='he_normal', + kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), + name='conv1')( + x) + x = layers.BatchNormalization( + axis=bn_axis, + momentum=batch_norm_decay, + epsilon=batch_norm_epsilon, + name='bn_conv1')( + x) + x = layers.Activation('relu')(x) + x = layers.MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x) + + x = conv_block( + x, 3, [64, 64, 256], stage=2, block='a', strides=(1, 1), **block_config) + x = identity_block(x, 3, [64, 64, 256], stage=2, block='b', **block_config) + x = identity_block(x, 3, [64, 64, 256], stage=2, block='c', **block_config) + + x = conv_block(x, 3, [128, 128, 512], stage=3, block='a', **block_config) + x = identity_block(x, 3, [128, 128, 512], stage=3, block='b', **block_config) + x = identity_block(x, 3, [128, 128, 512], stage=3, block='c', **block_config) + x = identity_block(x, 3, [128, 128, 512], stage=3, block='d', **block_config) + + x = conv_block(x, 3, [256, 256, 1024], stage=4, block='a', **block_config) + x = identity_block(x, 3, [256, 256, 1024], stage=4, block='b', **block_config) + x = identity_block(x, 3, [256, 256, 1024], stage=4, block='c', **block_config) + x = identity_block(x, 3, [256, 256, 1024], stage=4, block='d', **block_config) + x = identity_block(x, 3, [256, 256, 1024], stage=4, block='e', **block_config) + x = identity_block(x, 3, [256, 256, 1024], stage=4, block='f', **block_config) + + x = conv_block(x, 3, [512, 512, 2048], stage=5, block='a', **block_config) + x = identity_block(x, 3, [512, 512, 2048], stage=5, block='b', **block_config) + x = identity_block(x, 3, [512, 512, 2048], stage=5, block='c', **block_config) + + x = layers.GlobalAveragePooling2D()(x) + x = layers.Dense( + num_classes, + kernel_initializer=tf.compat.v1.keras.initializers.random_normal( + stddev=0.01), + kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), + bias_regularizer=_gen_l2_regularizer(use_l2_regularizer), + name='fc1000')( + x) + + # A softmax that is followed by the model loss must be done cannot be done + # in float16 due to numeric issues. So we pass dtype=float32. + x = layers.Activation('softmax', dtype='float32')(x) + + # Create model. + return tf.keras.Model(img_input, x, name='resnet50') \ No newline at end of file diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/resnet_runnable.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/resnet_runnable.py new file mode 100644 index 0000000000000000000000000000000000000000..6e06f8f7ac38ac01fcc3fae9ee512f262d723bc3 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/resnet_runnable.py @@ -0,0 +1,545 @@ +# Copyright 2019 The TensorFlow Authors. 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. +# ============================================================================== +# List of changes: +# - added profiling callbacks support + +# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company + +"""Runs a ResNet model on the ImageNet dataset using custom training loops.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import json +import os +from typing import Dict, Optional, Text + +import tensorflow as tf +from TensorFlow.common.modeling import performance +from TensorFlow.common.training import grad_utils +from TensorFlow.common.training import standard_runnable +from TensorFlow.common.training import utils +from TensorFlow.utils.flags import core as flags_core +from TensorFlow.computer_vision.common import imagenet_preprocessing +from TensorFlow.computer_vision.Resnets.resnet_keras import common +from TensorFlow.computer_vision.Resnets.resnet_keras import resnet_model +from TensorFlow.computer_vision.Resnets.resnet_keras.common import get_global_batch_size + + +try: + import horovod.tensorflow as hvd +except ImportError: + hvd = None +class ResnetRunnable(standard_runnable.StandardTrainable, + standard_runnable.StandardEvaluable): + """Implements the training and evaluation APIs for Resnet model.""" + + def __init__(self, flags_obj, time_callback, train_steps, epoch_steps, profiler_callback,mlperf_mlloger,mlperf_mllog): + standard_runnable.StandardTrainable.__init__(self, + flags_obj.use_tf_while_loop, + flags_obj.use_tf_function) + standard_runnable.StandardEvaluable.__init__(self, + flags_obj.use_tf_function) + + self.strategy = tf.distribute.get_strategy() + self.flags_obj = flags_obj + self.dtype = flags_core.get_tf_dtype(flags_obj) + self.time_callback = time_callback + self.profiler_callback = profiler_callback + self.first_step = True + self.warmup_train_dataset = None + self.warmup_train_iter = None + self.warmup_eval_dataset = None + self.warmup_eval_iter = None + + self.mlperf_mlloger, self.mlperf_mllog = mlperf_mlloger, mlperf_mllog + # Input pipeline related + batch_size = flags_obj.batch_size + if batch_size % self.strategy.num_replicas_in_sync != 0: + raise ValueError( + 'Batch size must be divisible by number of replicas : {}'.format( + self.strategy.num_replicas_in_sync)) + + # As auto rebatching is not supported in + # `experimental_distribute_datasets_from_function()` API, which is + # required when cloning dataset to multiple workers in eager mode, + # we use per-replica batch size. + self.batch_size = int(batch_size / self.strategy.num_replicas_in_sync) + + if self.flags_obj.use_synthetic_data: + self.input_fn = self.get_synth_input_fn(True) + else: + self.input_fn = imagenet_preprocessing.input_fn + + self.model = resnet_model.resnet50( + num_classes=imagenet_preprocessing.NUM_CLASSES, + batch_size=flags_obj.batch_size, + use_l2_regularizer=not flags_obj.single_l2_loss_op) + + mlperf_variable_map = self.get_mlperf_variable_map() + for weight in self.model.weights: + if ('moving_mean' not in weight.name) and ('moving_variance' not in weight.name): + mlperf_mlloger.event(key=mlperf_mllog.constants.WEIGHTS_INITIALIZATION, metadata={'tensor': mlperf_variable_map[weight.name.split(':')[0]]}) + + self.use_lars_optimizer = self.flags_obj.optimizer == 'LARS' + + self.optimizer = common.get_optimizer(flags_obj, + get_global_batch_size(flags_obj.batch_size), + train_steps,mlperf_mlloger,mlperf_mllog) + # Make sure iterations variable is created inside scope. + self.global_step = self.optimizer.iterations + self.train_steps = train_steps + + self.one_hot = False + self.label_smoothing = flags_obj.label_smoothing + if self.label_smoothing and self.label_smoothing > 0: + self.one_hot = True + + use_graph_rewrite = flags_obj.fp16_implementation == 'graph_rewrite' + if use_graph_rewrite and not flags_obj.use_tf_function: + raise ValueError('--fp16_implementation=graph_rewrite requires ' + '--use_tf_function to be true') + self.optimizer = performance.configure_optimizer( + self.optimizer, + use_float16=self.dtype == tf.float16, + use_graph_rewrite=use_graph_rewrite, + loss_scale=flags_core.get_loss_scale(flags_obj, default_for_fp16=128)) + + if self.flags_obj.report_accuracy_metrics: + self.train_loss = tf.keras.metrics.Mean('train_loss', dtype=tf.float32) + if self.one_hot: + self.train_accuracy = tf.keras.metrics.CategoricalAccuracy( + 'train_accuracy', dtype=tf.float32) + else: + self.train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy( + 'train_accuracy', dtype=tf.float32) + self.test_loss = tf.keras.metrics.Mean('test_loss', dtype=tf.float32) + else: + self.train_loss = None + self.train_accuracy = None + self.test_loss = None + + self.dist_eval = flags_obj.dist_eval + self.profile = flags_obj.profile + + if self.one_hot: + self.test_accuracy = tf.keras.metrics.CategoricalAccuracy( + 'test_accuracy', dtype=tf.float32) + else: + self.test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy( + 'test_accuracy', dtype=tf.float32) + self.eval_accuracy = 0 + + self.checkpoint = tf.train.Checkpoint( + model=self.model, optimizer=self.optimizer) + + self.local_loss_mean = tf.keras.metrics.Mean("local_loss_min", dtype=tf.float32) + + # Handling epochs. + self.epoch_steps = epoch_steps + self.epoch_helper = utils.EpochHelper(epoch_steps, self.global_step) + + self.num_acc_steps = flags_obj.num_acc_steps + if self.num_acc_steps > 1: + self.init_accumulation_variables() + + self.model_state = None + + def init_accumulation_variables(self): + self.cur_acc_step = tf.compat.v1.get_variable( + name='cur_acc_step', + shape=(), + dtype=tf.int32, + trainable=False, + initializer=tf.compat.v1.constant_initializer(value=0) + ) + self.accum_vars = [tf.compat.v1.get_variable( + name=tvar.name.split(':')[0] + '/accum', + shape=tvar.shape.as_list(), + dtype=tf.float32, + trainable=False, + initializer=tf.compat.v1.zeros_initializer()) for tvar in self.model.trainable_variables] + self.loss_acc = tf.compat.v1.get_variable( + name='loss_acc', + shape=(), + dtype=tf.float32, + trainable=False, + initializer=tf.compat.v1.constant_initializer(value=0.0) + ) + + def get_mlperf_variable_map(self): + try: + script_path = os.path.realpath(__file__) + head_tail = os.path.split(script_path) + mlperf_map_file = head_tail[0] + '/mlperf_variable_map.json' + with open(mlperf_map_file, mode='r') as file_handle: + json_content = file_handle.read() + mlperf_map = json.loads(json_content) + except IOError: + raise IOError(f"MLPerf variable map file: {mlperf_map_file} not accesible") + return mlperf_map + + def get_synth_input_fn(self, is_training): + return common.get_synth_input_fn( + height=imagenet_preprocessing.DEFAULT_IMAGE_SIZE, + width=imagenet_preprocessing.DEFAULT_IMAGE_SIZE, + num_channels=imagenet_preprocessing.NUM_CHANNELS, + num_classes=imagenet_preprocessing.NUM_CLASSES, + dtype=common.get_dl_type(self.flags_obj), + drop_remainder=is_training, + experimental_preloading=self.flags_obj.experimental_preloading) + + def build_train_dataset(self, synthetic=False, manifest_path=None): + """See base class.""" + return utils.make_distributed_dataset( + self.strategy, + self.input_fn, + is_training=True, + data_dir=self.flags_obj.data_dir, + jpeg_data_dir=self.flags_obj.jpeg_data_dir, + batch_size=self.batch_size, + model_dir=self.flags_obj.model_dir, + parse_record_fn=imagenet_preprocessing.parse_record, + datasets_num_private_threads=self.flags_obj + .datasets_num_private_threads, + dtype=common.get_dl_type(self.flags_obj), + drop_remainder=True, + dataset_cache=self.flags_obj.dataset_cache, + experimental_preloading=self.flags_obj.experimental_preloading, + num_train_files=self.flags_obj.num_train_files, + num_eval_files=self.flags_obj.num_eval_files, + synthetic=synthetic, + manifest_path=manifest_path) + + def build_synthetic_train_dataset(self): + return self.build_train_dataset(synthetic=True) + + def build_eval_dataset(self, synthetic=False): + """See base class.""" + return utils.make_distributed_dataset( + self.strategy, + self.input_fn, + is_training=False, + data_dir=self.flags_obj.data_dir, + jpeg_data_dir=self.flags_obj.jpeg_data_dir, + batch_size=self.batch_size, + model_dir=self.flags_obj.model_dir, + parse_record_fn=imagenet_preprocessing.parse_record, + dtype=common.get_dl_type(self.flags_obj), + dataset_cache=self.flags_obj.dataset_cache, + experimental_preloading=self.flags_obj.experimental_preloading, + num_train_files=self.flags_obj.num_train_files, + num_eval_files=self.flags_obj.num_eval_files, + synthetic=synthetic) + + def build_synthetic_eval_dataset(self): + return self.build_eval_dataset(synthetic=True) + + def get_prediction_loss(self, labels, logits, training=True): + if self.one_hot: + return tf.keras.losses.categorical_crossentropy( + labels, logits, label_smoothing=self.label_smoothing) + else: + return tf.keras.losses.sparse_categorical_crossentropy(labels, logits) + + def train_loop_begin(self): + """See base class.""" + # Reset all metrics + if self.train_loss: + self.train_loss.reset_states() + if self.train_accuracy: + self.train_accuracy.reset_states() + + self._epoch_begin() + self.time_callback.on_batch_begin(self.epoch_helper.batch_index) + if self.profiler_callback is not None: + self.profiler_callback.on_batch_begin(self.epoch_helper.batch_index) + + def train_step(self, iterator): + """See base class.""" + + def step_fn_broadcast(): + if hvd is not None and hvd.is_initialized(): + tf.cond(self.global_step == 1, + lambda: hvd.broadcast_variables(self.model.variables + self.optimizer.variables(), root_rank=0), + lambda: tf.constant(True)) + + def step_fn_modeling(): + if self.flags_obj.modeling: + sess = tf.compat.v1.Session() + # pbtxt generation + tf.io.write_graph(sess.graph.as_graph_def(add_shapes=True), self.flags_obj.model_dir, 'graph.pbtxt') + # meta graph generation + tf.compat.v1.train.export_meta_graph(filename='checkpoint_model.meta', meta_info_def=None, graph_def=None, saver_def=None, collection_list=None, as_text=False, graph=None, export_scope=None, clear_devices=False, clear_extraneous_savers=False, strip_default_attrs=False, save_debug_info=False) + + def step_fn_accumulation_steps_enabled(loss, tape): + grads = tape.gradient(loss, self.model.trainable_variables) + + if self.cur_acc_step == 0: + for i in range(len(self.accum_vars)): + self.accum_vars[i].assign(grads[i]) + else: # self.cur_acc_step > 0 + for i in range(len(self.accum_vars)): + self.accum_vars[i].assign_add(grads[i]) + + self.loss_acc.assign_add(loss) + self.cur_acc_step.assign_add(1) + + if self.cur_acc_step == self.num_acc_steps: + grads_and_vars = zip(self.accum_vars, self.model.trainable_variables) + self.optimizer.apply_gradients(grads_and_vars, experimental_aggregate_gradients=False) + + step_fn_broadcast() + step_fn_modeling() + + if self.train_loss: + self.train_loss.update_state(self.loss_acc) + + self.cur_acc_step.assign(0) + self.loss_acc.assign(0.0) + + def step_fn_accumulation_steps_disabled(loss, tape): + if hvd is not None and hvd.is_initialized(): + grads = tape.gradient(loss, self.model.trainable_variables) + grads_and_vars = zip(grads, self.model.trainable_variables) + self.optimizer.apply_gradients(grads_and_vars, experimental_aggregate_gradients=False) + else: + grad_utils.minimize_using_explicit_allreduce( + tape, self.optimizer, loss, self.model.trainable_variables) + + step_fn_broadcast() + step_fn_modeling() + + if self.train_loss: + self.train_loss.update_state(loss) + + def step_fn(inputs): + """Function to run on the device.""" + images, labels = inputs + if self.one_hot: + labels = tf.cast(labels, tf.int32) + labels = tf.one_hot(labels, 1001) + labels = tf.squeeze(labels) + + with tf.GradientTape() as tape: + logits = self.model(images, training=True) + prediction_loss = self.get_prediction_loss(labels, logits) + loss = tf.reduce_sum(prediction_loss) * (1.0 / self.flags_obj.batch_size) + + if not self.use_lars_optimizer: + num_replicas = self.strategy.num_replicas_in_sync + + if self.flags_obj.single_l2_loss_op: + l2_loss = self.flags_obj.weight_decay * tf.add_n([ + tf.nn.l2_loss(v) + for v in self.model.trainable_variables + if ('bn' not in v.name) + ]) + + loss += (l2_loss / num_replicas) + else: + loss += (tf.reduce_sum(self.model.losses) / num_replicas) + + loss = loss / self.num_acc_steps + + if hvd is not None and hvd.is_initialized(): + tape = hvd.DistributedGradientTape(tape) + + if self.num_acc_steps > 1: + step_fn_accumulation_steps_enabled(loss, tape) + else: + step_fn_accumulation_steps_disabled(loss, tape) + + if self.train_accuracy: + self.train_accuracy.update_state(labels, logits) + + self.strategy.run(step_fn, args=(next(iterator),)) + + def train_loop_end(self): + """See base class.""" + metrics = dict() + if self.train_loss: + metrics['train_loss'] = self.train_loss.result() + if self.train_accuracy: + metrics['train_accuracy'] = self.train_accuracy.result() + self.time_callback.on_batch_end(self.epoch_helper.batch_index - 1) + if self.profiler_callback is not None: + self.profiler_callback.on_batch_end(self.epoch_helper.batch_index - 1) + self._epoch_end() + return metrics + + def eval_begin(self): + """See base class.""" + if self.test_loss: + self.test_loss.reset_states() + self.test_accuracy.reset_states() + epoch_num = int(self.epoch_helper.current_epoch) + self.mlperf_mlloger.start( + key=self.mlperf_mllog.constants.EVAL_START, value=None, metadata={'epoch_num': epoch_num + 1}) + + def eval_step(self, iterator): + """See base class.""" + + def step_fn(inputs): + """Function to run on the device.""" + images, labels = inputs + if self.one_hot: + labels = tf.cast(labels, tf.int32) + labels = tf.one_hot(labels, 1001) + labels = tf.squeeze(labels) + + logits = self.model(images, training=False) + loss = self.get_prediction_loss(labels, logits, training=False) + loss = tf.reduce_sum(loss) * (1.0 / self.flags_obj.batch_size) + if self.test_loss: + self.test_loss.update_state(loss) + self.test_accuracy.update_state(labels, logits) + + self.strategy.run(step_fn, args=(next(iterator),)) + + def eval_end(self): + """See base class.""" + epoch_num = int(self.epoch_helper.current_epoch) + self.mlperf_mlloger.end( + key=self.mlperf_mllog.constants.EVAL_STOP, value=None, metadata={'epoch_num': epoch_num + 1}) + + local_hit = self.test_accuracy.total + local_count = self.test_accuracy.count + + global_hit = local_hit + global_count = local_count + if hvd is not None and hvd.is_initialized() and self.dist_eval: + global_hit = hvd.allreduce(local_hit, op=hvd.Sum) + global_count = hvd.allreduce(local_count, op=hvd.Sum) + global_accuracy = float(global_hit / global_count) + + # assign to self + self.test_accuracy.total.assign(global_hit) + self.test_accuracy.count.assign(global_count) + + eval_accuracy = global_accuracy + self.eval_accuracy = eval_accuracy + self.mlperf_mlloger.event( + key=self.mlperf_mllog.constants.EVAL_ACCURACY, value=eval_accuracy, metadata={'epoch_num': epoch_num + 1}) + + first_epoch_num = max(epoch_num - self.flags_obj.epochs_between_evals + 1, 0) + epoch_count = self.flags_obj.epochs_between_evals + if first_epoch_num == 0: + epoch_count = self.flags_obj.eval_offset_epochs + if epoch_count == 0: + epoch_count = self.flags_obj.epochs_between_evals + self.mlperf_mlloger.end( + key=self.mlperf_mllog.constants.BLOCK_STOP, + value=None, + metadata={ + 'first_epoch_num': first_epoch_num + 1, + 'epoch_count': epoch_count + }) + + past_threshold = False + if self.flags_obj.target_accuracy is not None: + past_threshold = eval_accuracy >= self.flags_obj.target_accuracy + if (hvd is not None and hvd.is_initialized() and (not self.dist_eval) ): + past_threshold = hvd.allreduce(tf.cast(past_threshold, tf.float32), + op=hvd.Sum) > 0 + + continue_training = True + if past_threshold: + continue_training = False + elif ( (not self.profile) and eval_accuracy <= 0.002): + continue_training = False + elif self.global_step.numpy() < self.train_steps: + self.mlperf_mlloger.start( + key=self.mlperf_mllog.constants.BLOCK_START, + value=None, + metadata={ + 'first_epoch_num': epoch_num + 2, + 'epoch_count': self.flags_obj.epochs_between_evals + }) + + metrics = { + 'test_accuracy': eval_accuracy, + 'continue_training': continue_training, + } + if self.test_loss: + metrics['test_loss'] = self.test_loss.result() + return metrics + + def warmup(self, num_steps: Optional[tf.Tensor]) -> Optional[Dict[Text, tf.Tensor]]: + """Implements device warmup with multiple steps. + + This loop runs the input pipeline on synthetic data before training, thereby + allowing tf.function tracing before the dataset is accessed. + + Args: + num_steps: A guideline for how many training steps to run. Note that it is + up to the model what constitutes a "step" (this may involve more than + one update to model parameters, e.g. if training a GAN). + + Returns: + The function may return a dictionary of `Tensors`, which will be + written to logs and as TensorBoard summaries. + """ + self.model_state = [weight.numpy() for weight in self.model.weights] + + if self.warmup_train_dataset is None: + self.warmup_train_dataset = self.build_synthetic_train_dataset() + self.warmup_train_iter = tf.nest.map_structure(iter, self.warmup_train_dataset) + + if self.train_loop_fn is None: + train_fn = self.train_step + if self.use_tf_while_loop: + self.train_loop_fn = utils.create_tf_while_loop_fn(train_fn) + else: + if self.use_tf_function: + train_fn = tf.function(train_fn) + self.train_loop_fn = utils.create_loop_fn(train_fn) + + self.train_loop_fn(self.warmup_train_iter, num_steps) + + if self.warmup_eval_dataset is None: + self.warmup_eval_dataset = self.build_synthetic_eval_dataset() + self.warmup_eval_iter = tf.nest.map_structure(iter, self.warmup_eval_dataset) + + if self.eval_loop_fn is None: + eval_fn = self.eval_step + if self.eval_use_tf_function: + eval_fn = tf.function(eval_fn) + self.eval_loop_fn = utils.create_loop_fn(eval_fn) + + self.eval_loop_fn(self.warmup_eval_iter, num_steps) + + return self.warmup_loop_end() + + def warmup_loop_end(self): + """See base class.""" + # Reset the state + for weight, state in zip(self.model.weights, self.model_state): + weight.assign(state) + for weight in self.optimizer.weights: + weight.assign(tf.zeros(shape=weight.shape, dtype=weight.dtype)) + + def _epoch_begin(self): + if self.epoch_helper.epoch_begin(): + self.time_callback.on_epoch_begin(self.epoch_helper.current_epoch) + if self.profiler_callback is not None: + self.profiler_callback.on_epoch_begin(self.epoch_helper.current_epoch) + + def _epoch_end(self): + if self.epoch_helper.epoch_end(): + self.time_callback.on_epoch_end(self.epoch_helper.current_epoch) + if self.profiler_callback is not None: + self.profiler_callback.on_epoch_end(self.epoch_helper.current_epoch) diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/utils/__init__.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/utils/optimizers/keras/backward_compatibility.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/utils/optimizers/keras/backward_compatibility.py new file mode 100644 index 0000000000000000000000000000000000000000..6b5a724580cf8d08dbdf19986bd3ff525206c537 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/utils/optimizers/keras/backward_compatibility.py @@ -0,0 +1,9 @@ +# Copyright (C) 2023 Habana Labs, Ltd. an Intel Company + +from packaging import version +import tensorflow as tf + +if version.parse(tf.__version__) <= version.parse("2.12.0"): + from tensorflow.python.framework.ops import convert_to_tensor_v2 +else: + from tensorflow.python.framework.tensor_conversion import convert_to_tensor_v2 diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/utils/optimizers/keras/lars_optimizer.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/utils/optimizers/keras/lars_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..3ba1f16b0d1857b1f08eaa30e0f5595528d44921 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/utils/optimizers/keras/lars_optimizer.py @@ -0,0 +1,225 @@ +# Copyright 2018 The TensorFlow Authors. 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. +# ============================================================================== +"""Layer-wise Adaptive Rate Scaling optimizer for large-batch training.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import tensorflow as tf +from tensorflow.python.training import training_ops + + +class LARSOptimizer(tf.keras.optimizers.legacy.Optimizer): + """Layer-wise Adaptive Rate Scaling for large batch training. + + Introduced by "Large Batch Training of Convolutional Networks" by Y. You, + I. Gitman, and B. Ginsburg. (https://arxiv.org/abs/1708.03888) + + Implements the LARS learning rate scheme presented in the paper above. This + optimizer is useful when scaling the batch size to up to 32K without + significant performance degradation. It is recommended to use the optimizer + in conjunction with: + - Gradual learning rate warm-up + - Linear learning rate scaling + - Poly rule learning rate decay + + Note, LARS scaling is currently only enabled for dense tensors. Sparse tensors + use the default momentum optimizer. + """ + + def __init__( + self, + learning_rate, + momentum=0.9, + weight_decay=0.0001, + # The LARS coefficient is a hyperparameter + eeta=0.001, + epsilon=0.0, + name="LARSOptimizer", + # Enable skipping variables from LARS scaling. + # TODO(sameerkm): Enable a direct mechanism to pass a + # subset of variables to the optimizer. + skip_list=None, + use_nesterov=False, + **kwargs): + """Construct a new LARS Optimizer. + + Args: + learning_rate: A `Tensor`, floating point value, or a schedule that is a + `tf.keras.optimizers.schedules.LearningRateSchedule`, or a callable + that takes no arguments and returns the actual value to use. The + learning rate. + momentum: A floating point value. Momentum hyperparameter. + weight_decay: A floating point value. Weight decay hyperparameter. + eeta: LARS coefficient as used in the paper. Dfault set to LARS + coefficient from the paper. (eeta / weight_decay) determines the highest + scaling factor in LARS. + epsilon: Optional epsilon parameter to be set in models that have very + small gradients. Default set to 0.0. + name: Optional name prefix for variables and ops created by LARSOptimizer. + skip_list: List of strings to enable skipping variables from LARS scaling. + If any of the strings in skip_list is a subset of var.name, variable + 'var' is skipped from LARS scaling. For a typical classification model + with batch normalization, the skip_list is ['batch_normalization', + 'bias'] + use_nesterov: when set to True, nesterov momentum will be enabled + **kwargs: keyword arguments. + + Raises: + ValueError: If a hyperparameter is set to a non-sensical value. + """ + if momentum < 0.0: + raise ValueError("momentum should be positive: %s" % momentum) + if weight_decay < 0.0: + raise ValueError("weight_decay should be positive: %s" % weight_decay) + super(LARSOptimizer, self).__init__(name=name, **kwargs) + + self._set_hyper("learning_rate", learning_rate) + + # When directly using class members, instead of + # _set_hyper and _get_hyper (such as learning_rate above), + # the values are fixed after __init(), and not being + # updated during the training process. + # This provides better performance but less flexibility. + self.momentum = momentum + self.weight_decay = weight_decay + self.eeta = eeta + self.epsilon = epsilon or tf.keras.backend.epsilon() + self._skip_list = skip_list + self.use_nesterov = use_nesterov + + def _prepare_local(self, var_device, var_dtype, apply_state): + lr_t = self._get_hyper("learning_rate", var_dtype) + local_step = tf.cast(self.iterations, var_dtype) + lr_t = tf.cast(lr_t(local_step), var_dtype) + learning_rate_t = tf.identity(lr_t) + + apply_state[(var_device, var_dtype)].update( + dict( + learning_rate=learning_rate_t, + )) + + def _create_slots(self, var_list): + for v in var_list: + self.add_slot(v, "momentum") + + def compute_lr(self, grad, var, coefficients): + scaled_lr = coefficients["learning_rate"] + if self._skip_list is None or not any(v in var.name + for v in self._skip_list): + w_norm = tf.norm(var, ord=2) + g_norm = tf.norm(grad, ord=2) + trust_ratio = tf.where( + tf.greater(w_norm, 0), + tf.where( + tf.greater(g_norm, 0), + (self.eeta * w_norm / + (g_norm + self.weight_decay * w_norm + self.epsilon)), 1.0), 1.0) + + scaled_lr = coefficients["learning_rate"] * trust_ratio + # Add the weight regularization gradient + grad = grad + self.weight_decay * var + return scaled_lr, grad + + def _apply_dense(self, grad, var, apply_state=None): + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) + or self._fallback_apply_state(var_device, var_dtype)) + + scaled_lr, grad = self.compute_lr(grad, var, coefficients) + mom = self.get_slot(var, "momentum") + return training_ops.apply_momentum( + var, + mom, + tf.cast(1.0, var.dtype.base_dtype), + grad * scaled_lr, + self.momentum, + use_locking=False, + use_nesterov=self.use_nesterov) + + def _resource_apply_dense(self, grad, var, apply_state=None): + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) + or self._fallback_apply_state(var_device, var_dtype)) + + scaled_lr, grad = self.compute_lr(grad, var, coefficients) + mom = self.get_slot(var, "momentum") + + # ============================================================ + return training_ops.resource_apply_keras_momentum( + var.handle, + mom.handle, + scaled_lr, + grad, + self.momentum, + use_locking=False, + use_nesterov=self.use_nesterov) + # ============================================================ + + # ============================================================ + # mom_t = mom * self.momentum - grad * scaled_lr + # mom_t = state_ops.assign(mom, mom_t, use_locking=False) + # if self.use_nesterov: + # var_t = var + mom_t * self.momentum - grad * scaled_lr + # else: + # var_t = var + mom_t + # return state_ops.assign(var, var_t, use_locking=False).op + # ============================================================ + + # Fallback to momentum optimizer for sparse tensors + def _apply_sparse(self, grad, var, apply_state=None): + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) + or self._fallback_apply_state(var_device, var_dtype)) + + mom = self.get_slot(var, "momentum") + return training_ops.sparse_apply_momentum( + var, + mom, + coefficients["learning_rate"], + grad.values, + grad.indices, + self.momentum, + use_locking=False, + use_nesterov=self.use_nesterov) + + def _resource_apply_sparse(self, grad, var, indices, apply_state=None): + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) + or self._fallback_apply_state(var_device, var_dtype)) + + mom = self.get_slot(var, "momentum") + return training_ops.resource_sparse_apply_keras_momentum( + var.handle, + mom.handle, + coefficients["learning_rate"], + grad, + indices, + self.momentum, + use_locking=False, + use_nesterov=self.use_nesterov) + + def get_config(self): + config = super(LARSOptimizer, self).get_config() + config.update({ + "learning_rate": self._serialize_hyperparameter("learning_rate"), + "momentum": self.momentum, + "weight_decay": self.weight_decay, + "eeta": self.eeta, + "epsilon": self.epsilon, + "use_nesterov": self.use_nesterov, + }) + return config diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/utils/optimizers/keras/lars_util.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/utils/optimizers/keras/lars_util.py new file mode 100644 index 0000000000000000000000000000000000000000..c6f70059d08d3c2175b56a82b9bdaa14b95054c6 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/utils/optimizers/keras/lars_util.py @@ -0,0 +1,183 @@ +# Copyright 2018 The TensorFlow Authors. 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 (C) 2023 Habana Labs, Ltd. an Intel Company +# ============================================================================== +"""Enable Layer-wise Adaptive Rate Scaling optimizer in ResNet.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from absl import flags +import tensorflow as tf +from TensorFlow.computer_vision.Resnets.utils.optimizers.keras import backward_compatibility + +from tensorflow.python.eager import context +from tensorflow.python.framework import ops +from tensorflow.python.ops import math_ops +FLAGS = flags.FLAGS + + +def define_lars_flags(): + """Defines flags needed by LARS optimizer.""" + + flags.DEFINE_float( + 'end_learning_rate', + default=None, + help=('Polynomial decay end learning rate.')) + + flags.DEFINE_float( + 'lars_epsilon', default=0.0, help=('Override autoselected LARS epsilon.')) + + flags.DEFINE_float( + 'warmup_epochs', + default=None, + help=('Override autoselected polynomial decay warmup epochs.')) + + flags.DEFINE_float( + 'momentum', + default=0.9, + help=('Momentum parameter used in the MomentumOptimizer.')) + + flags.DEFINE_float( + 'lars_decay_epochs', + default=None, + help=('Momentum parameter used in the MomentumOptimizer.')) + + +class PolynomialDecayWithWarmup( + tf.keras.optimizers.schedules.LearningRateSchedule): + """A LearningRateSchedule that uses a polynomial decay with warmup.""" + + def __init__(self, + batch_size, + steps_per_epoch, + train_steps, + initial_learning_rate=None, + end_learning_rate=None, + warmup_epochs=None, + compute_lr_on_cpu=False, + name=None, + mlperf_mlloger=None, + mlperf_mllog=None): + """Applies a polynomial decay to the learning rate with warmup.""" + super(PolynomialDecayWithWarmup, self).__init__() + + self.batch_size = batch_size + self.steps_per_epoch = steps_per_epoch + self.train_steps = train_steps + self.name = name + self.learning_rate_ops_cache = {} + self.compute_lr_on_cpu = compute_lr_on_cpu + + if batch_size < 16384: + self.initial_learning_rate = 10.0 + warmup_epochs_ = 5 + elif batch_size < 32768: + self.initial_learning_rate = 25.0 + warmup_epochs_ = 5 + else: + self.initial_learning_rate = 31.2 + warmup_epochs_ = 25 + + # Override default poly learning rate and warmup epochs + if initial_learning_rate: + self.initial_learning_rate = initial_learning_rate + + if end_learning_rate: + self.end_learning_rate = end_learning_rate + else: + self.end_learning_rate = 0.0001 + + if warmup_epochs is not None: + warmup_epochs_ = warmup_epochs + self.warmup_epochs = warmup_epochs_ + + opt_name = FLAGS.optimizer.lower() + mlperf_mlloger.event(key=mlperf_mllog.constants.OPT_NAME, value=opt_name) + + warmup_steps = warmup_epochs_ * steps_per_epoch + self.warmup_steps = tf.cast(warmup_steps, tf.float32) + if (FLAGS.lars_decay_epochs is None): + self.decay_steps = train_steps + else: + self.decay_steps = FLAGS.lars_decay_epochs * steps_per_epoch + self.decay_steps = self.decay_steps - warmup_steps + 1 + + if opt_name == 'lars': + mlperf_mlloger.event(key=mlperf_mllog.constants.LARS_EPSILON, value=FLAGS.lars_epsilon) + mlperf_mlloger.event(key=mlperf_mllog.constants.LARS_OPT_WEIGHT_DECAY, value=FLAGS.weight_decay) + mlperf_mlloger.event(key=mlperf_mllog.constants.LARS_OPT_END_LR, value=self.end_learning_rate) + mlperf_mlloger.event(key=mlperf_mllog.constants.LARS_OPT_LR_DECAY_STEPS, value=int(self.decay_steps)) + mlperf_mlloger.event(key=mlperf_mllog.constants.LARS_OPT_LR_DECAY_POLY_POWER, value=2.0) + mlperf_mlloger.event(key='lars_opt_momentum', value=FLAGS.momentum) + elif opt_name == 'sgd': + mlperf_mlloger.event(key=mlperf_mllog.constants.OPT_WEIGHT_DECAY, value=FLAGS.weight_decay) + mlperf_mlloger.event(key='opt_momentum', value=FLAGS.momentum) + else: + print('NOT Supported') + mlperf_mlloger.event(key=opt_name+'_'+mlperf_mllog.constants.OPT_LR_WARMUP_EPOCHS, value=warmup_epochs_) + mlperf_mlloger.event(key=opt_name+'_'+mlperf_mllog.constants.OPT_BASE_LR, value=self.initial_learning_rate) + + self.poly_rate_scheduler = tf.keras.optimizers.schedules.PolynomialDecay( + initial_learning_rate=self.initial_learning_rate, + decay_steps=self.decay_steps, + end_learning_rate=self.end_learning_rate, + power=2.0) + + def __call__(self, step): + if tf.executing_eagerly(): + return self._get_learning_rate(step) + + # In an eager function or graph, the current implementation of optimizer + # repeatedly call and thus create ops for the learning rate schedule. To + # avoid this, we cache the ops if not executing eagerly. + graph = tf.compat.v1.get_default_graph() + if graph not in self.learning_rate_ops_cache: + if self.compute_lr_on_cpu: + with tf.device('/device:CPU:0'): + self.learning_rate_ops_cache[graph] = self._get_learning_rate(step) + else: + self.learning_rate_ops_cache[graph] = self._get_learning_rate(step) + return self.learning_rate_ops_cache[graph] + + def _get_learning_rate(self, step): + with ops.name_scope_v2(self.name or 'PolynomialDecayWithWarmup') as name: + + initial_learning_rate = backward_compatibility.convert_to_tensor_v2( + self.initial_learning_rate, name='initial_learning_rate') + warmup_steps = backward_compatibility.convert_to_tensor_v2( + self.warmup_steps, name='warmup_steps') + + warmup_rate = ( + initial_learning_rate * step / warmup_steps) + + poly_steps = math_ops.maximum(math_ops.subtract(step, warmup_steps), 1) + poly_rate = self.poly_rate_scheduler(poly_steps) + + decay_rate = tf.where(step <= warmup_steps, + warmup_rate, poly_rate, name=name) + return decay_rate + + def get_config(self): + return { + 'batch_size': self.batch_size, + 'steps_per_epoch': self.steps_per_epoch, + 'train_steps': self.train_steps, + 'initial_learning_rate': self.initial_learning_rate, + 'end_learning_rate': self.end_learning_rate, + 'warmup_epochs': self.warmup_epochs, + 'name': self.name, + } diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/__init__.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/common/imagenet_preprocessing.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/common/imagenet_preprocessing.py new file mode 100644 index 0000000000000000000000000000000000000000..28c3131d2cd0923b3cb374984d16de72a0629767 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/common/imagenet_preprocessing.py @@ -0,0 +1,680 @@ +# Copyright 2016 The TensorFlow Authors. 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. +# ============================================================================== +# List of changes: +# - added support for prefetching to HPU +# - flags to control image preprocessing +# - flag to influence parallelism of dataset processing + +# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company + + +"""Provides utilities to preprocess images. + +Training images are sampled using the provided bounding boxes, and subsequently +cropped to the sampled bounding box. Images are additionally flipped randomly, +then resized to the target output size (without aspect-ratio preservation). + +Images used during evaluation are resized (with aspect-ratio preservation) and +centrally cropped. + +All images undergo mean color subtraction. + +Note that these steps are colloquially referred to as "ResNet preprocessing," +and they differ from "VGG preprocessing," which does not use bounding boxes +and instead does an aspect-preserving resize followed by random crop during +training. (These both differ from "Inception preprocessing," which introduces +color distortion steps.) + +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import uuid +from absl import flags +from absl import logging +import tensorflow as tf +from habana_frameworks.tensorflow.media import habana_imagenet_dataset + +from habana_frameworks.tensorflow.multinode_helpers import comm_size + +try: + import horovod.tensorflow as hvd +except ImportError: + hvd = None + +DEFAULT_IMAGE_SIZE = 224 +NUM_CHANNELS = 3 +NUM_CLASSES = 1001 + +NUM_IMAGES = { + 'train': 1281167, + 'validation': 50000, +} + +_SHUFFLE_BUFFER = 10000 + +_R_MEAN = 123.68 +_G_MEAN = 116.78 +_B_MEAN = 103.94 +CHANNEL_MEANS = [_R_MEAN, _G_MEAN, _B_MEAN] + +# The lower bound for the smallest side of the image for aspect-preserving +# resizing. For example, if an image is 500 x 1000, it will be resized to +# _RESIZE_MIN x (_RESIZE_MIN * 2). +_RESIZE_MIN = 256 + +flags.DEFINE_integer(name='dataset_parallel_calls', default=tf.data.experimental.AUTOTUNE, help='Determines the number of parallel calls in dataset operations') + + +def process_record_dataset(dataset, + is_training, + batch_size, + shuffle_buffer, + parse_record_fn, + dtype=tf.float32, + datasets_num_private_threads=None, + drop_remainder=False, + tf_data_experimental_slack=False, + experimental_preloading=False): + """Given a Dataset with raw records, return an iterator over the records. + + Args: + dataset: A Dataset representing raw records + is_training: A boolean denoting whether the input is for training. + batch_size: The number of samples per batch. + shuffle_buffer: The buffer size to use when shuffling records. A larger + value results in better randomness, but smaller values reduce startup + time and use less memory. + parse_record_fn: A function that takes a raw record and returns the + corresponding (image, label) pair. + dtype: Data type to use for images/features. + datasets_num_private_threads: Number of threads for a private + threadpool created for all datasets computation. + drop_remainder: A boolean indicates whether to drop the remainder of the + batches. If True, the batch dimension will be static. + tf_data_experimental_slack: Whether to enable tf.data's + `experimental_slack` option. + + Returns: + Dataset of (image, label) pairs ready for iteration. + """ + # Defines a specific size thread pool for tf.data operations. + if datasets_num_private_threads: + options = tf.data.Options() + options.experimental_threading.private_threadpool_size = ( + datasets_num_private_threads) + dataset = dataset.with_options(options) + logging.info( + 'datasets_num_private_threads: %s', datasets_num_private_threads) + + if is_training: + # Shuffles records before repeating to respect epoch boundaries. + dataset = dataset.shuffle(buffer_size=shuffle_buffer) + # Repeats the dataset for the number of epochs to train. + dataset = dataset.repeat() + + num_parallel_calls = flags.FLAGS.dataset_parallel_calls + if hvd is not None and hvd.is_initialized(): + num_parallel_calls = 16 + # Parses the raw records into images and labels. + dataset = dataset.map( + lambda value: parse_record_fn(value, is_training, dtype), + num_parallel_calls=num_parallel_calls, deterministic=False) + dataset = dataset.batch(batch_size, drop_remainder=drop_remainder) + + # Operations between the final prefetch and the get_next call to the iterator + # will happen synchronously during run time. We prefetch here again to + # background all of the above processing work and keep it out of the + # critical training path. Setting buffer_size to tf.data.experimental.AUTOTUNE + # allows DistributionStrategies to adjust how many batches to fetch based + # on how many devices are present. + if experimental_preloading: + device = "/device:HPU:0" + with tf.device(device): + dataset = dataset.apply(tf.data.experimental.prefetch_to_device(device)) + else: + dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE) + + options = tf.data.Options() + options.experimental_slack = tf_data_experimental_slack + dataset = dataset.with_options(options) + + return dataset + + +def get_filenames(is_training, data_dir, num_train_files, num_eval_files): + """Return filenames for dataset.""" + if is_training: + return [ + os.path.join(data_dir, 'train/train-%05d-of-%05d' % (i, num_train_files)) + for i in range(num_train_files)] + else: + return [ + os.path.join(data_dir, 'validation/validation-%05d-of-%05d' % (i, num_eval_files)) + for i in range(num_eval_files)] + + +def parse_example_proto(example_serialized): + """Parses an Example proto containing a training example of an image. + + The output of the build_image_data.py image preprocessing script is a dataset + containing serialized Example protocol buffers. Each Example proto contains + the following fields (values are included as examples): + + image/height: 462 + image/width: 581 + image/colorspace: 'RGB' + image/channels: 3 + image/class/label: 615 + image/class/synset: 'n03623198' + image/class/text: 'knee pad' + image/object/bbox/xmin: 0.1 + image/object/bbox/xmax: 0.9 + image/object/bbox/ymin: 0.2 + image/object/bbox/ymax: 0.6 + image/object/bbox/label: 615 + image/format: 'JPEG' + image/filename: 'ILSVRC2012_val_00041207.JPEG' + image/encoded: + + Args: + example_serialized: scalar Tensor tf.string containing a serialized + Example protocol buffer. + + Returns: + image_buffer: Tensor tf.string containing the contents of a JPEG file. + label: Tensor tf.int32 containing the label. + bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] + where each coordinate is [0, 1) and the coordinates are arranged as + [ymin, xmin, ymax, xmax]. + """ + # Dense features in Example proto. + feature_map = { + 'image/encoded': tf.io.FixedLenFeature([], dtype=tf.string, + default_value=''), + 'image/class/label': tf.io.FixedLenFeature([], dtype=tf.int64, + default_value=-1), + 'image/class/text': tf.io.FixedLenFeature([], dtype=tf.string, + default_value=''), + } + sparse_float32 = tf.io.VarLenFeature(dtype=tf.float32) + # Sparse features in Example proto. + feature_map.update( + {k: sparse_float32 for k in [ + 'image/object/bbox/xmin', 'image/object/bbox/ymin', + 'image/object/bbox/xmax', 'image/object/bbox/ymax']}) + + features = tf.io.parse_single_example(serialized=example_serialized, + features=feature_map) + label = tf.cast(features['image/class/label'], dtype=tf.int32) + + xmin = tf.expand_dims(features['image/object/bbox/xmin'].values, 0) + ymin = tf.expand_dims(features['image/object/bbox/ymin'].values, 0) + xmax = tf.expand_dims(features['image/object/bbox/xmax'].values, 0) + ymax = tf.expand_dims(features['image/object/bbox/ymax'].values, 0) + + # Note that we impose an ordering of (y, x) just to make life difficult. + bbox = tf.concat([ymin, xmin, ymax, xmax], 0) + + # Force the variable number of bounding boxes into the shape + # [1, num_boxes, coords]. + bbox = tf.expand_dims(bbox, 0) + bbox = tf.transpose(a=bbox, perm=[0, 2, 1]) + + return features['image/encoded'], label, bbox + + +def parse_record(raw_record, is_training, dtype): + """Parses a record containing a training example of an image. + + The input record is parsed into a label and image, and the image is passed + through preprocessing steps (cropping, flipping, and so on). + + Args: + raw_record: scalar Tensor tf.string containing a serialized + Example protocol buffer. + is_training: A boolean denoting whether the input is for training. + dtype: data type to use for images/features. + + Returns: + Tuple with processed image tensor in a channel-last format and + one-hot-encoded label tensor. + """ + image_buffer, label, bbox = parse_example_proto(raw_record) + + image = preprocess_image( + image_buffer=image_buffer, + bbox=bbox, + output_height=DEFAULT_IMAGE_SIZE, + output_width=DEFAULT_IMAGE_SIZE, + num_channels=NUM_CHANNELS, + is_training=is_training) + image = tf.cast(image, dtype) + + # Subtract one so that labels are in [0, 1000), and cast to float32 for + # Keras model. + label = tf.cast(tf.cast(tf.reshape(label, shape=[1]), dtype=tf.int32) - 1, + dtype=tf.float32) + return image, label + + +def get_parse_record_fn(use_keras_image_data_format=False): + """Get a function for parsing the records, accounting for image format. + + This is useful by handling different types of Keras models. For instance, + the current resnet_model.resnet50 input format is always channel-last, + whereas the keras_applications mobilenet input format depends on + tf.keras.backend.image_data_format(). We should set + use_keras_image_data_format=False for the former and True for the latter. + + Args: + use_keras_image_data_format: A boolean denoting whether data format is keras + backend image data format. If False, the image format is channel-last. If + True, the image format matches tf.keras.backend.image_data_format(). + + Returns: + Function to use for parsing the records. + """ + def parse_record_fn(raw_record, is_training, dtype): + image, label = parse_record(raw_record, is_training, dtype) + if use_keras_image_data_format: + if tf.keras.backend.image_data_format() == 'channels_first': + image = tf.transpose(image, perm=[2, 0, 1]) + return image, label + return parse_record_fn + + +def imagenet_dataset_fallback(is_training, + data_dir, + batch_size, + dtype=tf.float32, + datasets_num_private_threads=None, + parse_record_fn=parse_record, + input_context=None, + drop_remainder=False, + tf_data_experimental_slack=False, + dataset_cache=True, + filenames=None, + experimental_preloading=False, + num_train_files=1024, + num_eval_files=128, + use_distributed_eval=False): + + if filenames is None: + filenames = get_filenames(is_training, data_dir, num_train_files, num_eval_files) + dataset = tf.data.Dataset.from_tensor_slices(filenames) + + if (is_training or use_distributed_eval) and hvd is not None and hvd.is_initialized(): + logging.info( + 'HVD sharding the dataset: input_pipeline_id=%d num_input_pipelines=%d', + hvd.rank(), hvd.size()) + dataset = dataset.shard(hvd.size(), hvd.rank()) + + if input_context: + logging.info( + 'Sharding the dataset: input_pipeline_id=%d num_input_pipelines=%d', + input_context.input_pipeline_id, input_context.num_input_pipelines) + dataset = dataset.shard(input_context.num_input_pipelines, + input_context.input_pipeline_id) + + if is_training: + # Shuffle the input files + dataset = dataset.shuffle(buffer_size=num_train_files) + + # Convert to individual records. + # cycle_length = 10 means that up to 10 files will be read and deserialized in + # parallel. You may want to increase this number if you have a large number of + # CPU cores. + cycle_length = 10 + if hvd is not None and hvd.is_initialized(): + if is_training: + cycle_length = num_train_files // comm_size() + else: + cycle_length = num_eval_files // comm_size() + cycle_length = min(cycle_length, 10) + dataset = dataset.interleave( + tf.data.TFRecordDataset, + cycle_length=cycle_length, + num_parallel_calls=flags.FLAGS.dataset_parallel_calls) + + if dataset_cache: + # Improve performance when training and eval data is in remote storage and + # can fit into worker memory. + dataset = dataset.cache() + + return process_record_dataset( + dataset=dataset, + is_training=is_training, + batch_size=batch_size, + shuffle_buffer=_SHUFFLE_BUFFER, + parse_record_fn=parse_record_fn, + dtype=dtype, + datasets_num_private_threads=datasets_num_private_threads, + drop_remainder=drop_remainder, + tf_data_experimental_slack=tf_data_experimental_slack, + experimental_preloading=experimental_preloading + ) + + +def fetch_synth_data(is_training: bool, batch_size: int, model_dir, dtype) -> str: + """A function that generates and stores synthetic data + + Args: + is_training: A boolean denoting whether the input is for training. + batch_size: The number of samples per batch + dtype: Data type to use for images/features + + Returns: + Path to synthetic data + """ + root_path = f'{model_dir}/resnet_synth_data' + batch_class_name = f'{uuid.uuid4()}' + batch_path = f'{root_path}/train/{batch_class_name}/' if is_training else f'{root_path}/val/{batch_class_name}' + + os.makedirs(batch_path, exist_ok=True) + for i in range(batch_size): + input = tf.random.truncated_normal([DEFAULT_IMAGE_SIZE, DEFAULT_IMAGE_SIZE, NUM_CHANNELS], + dtype=dtype, + mean=127, + stddev=60, + name='synthetic_inputs') + casted_input = tf.cast(input, tf.uint8).numpy() + encode = tf.image.encode_jpeg(casted_input, format='rgb', quality=95).numpy() + filename = f'{batch_class_name}_{i}.JPEG' + with open(f'{batch_path}/{filename}', 'w+b') as fd: + fd.write(encode) + return root_path + +def input_fn(is_training, + data_dir, + jpeg_data_dir, + batch_size, + model_dir, + dtype=tf.float32, + datasets_num_private_threads=None, + parse_record_fn=parse_record, + input_context=None, + drop_remainder=False, + tf_data_experimental_slack=False, + dataset_cache=True, + filenames=None, + experimental_preloading=False, + num_train_files=1024, + num_eval_files=128, + synthetic=False, + manifest_path=None): + """Input function which provides batches for train or eval. + + Args: + is_training: A boolean denoting whether the input is for training. + data_dir: The directory containing the input data. + batch_size: The number of samples per batch. + dtype: Data type to use for images/features + datasets_num_private_threads: Number of private threads for tf.data. + parse_record_fn: Function to use for parsing the records. + input_context: A `tf.distribute.InputContext` object passed in by + `tf.distribute.Strategy`. + drop_remainder: A boolean indicates whether to drop the remainder of the + batches. If True, the batch dimension will be static. + tf_data_experimental_slack: Whether to enable tf.data's + `experimental_slack` option. + dataset_cache: Whether to cache the training and eval datasets on workers. + Typically used to improve performance when training and eval data is in + remote storage and can fit into worker memory. + filenames: Optional field for providing the file names of the TFRecords. + synthetic: A boolean that determines whether synthetic data should be generated. + + Returns: + A dataset that can be used for iteration. + """ + jpeg_data_path = fetch_synth_data(is_training, batch_size, model_dir, dtype) if synthetic else jpeg_data_dir + return habana_imagenet_dataset(fallback=imagenet_dataset_fallback, + is_training=is_training, + tf_data_dir=data_dir, + jpeg_data_dir=jpeg_data_path, + batch_size=batch_size, + num_channels=NUM_CHANNELS, + img_size=DEFAULT_IMAGE_SIZE, + dtype=dtype, + use_distributed_eval=flags.FLAGS.dist_eval, + datasets_num_private_threads=datasets_num_private_threads, + parse_record_fn=parse_record_fn, + input_context=input_context, + drop_remainder=drop_remainder, + tf_data_experimental_slack=tf_data_experimental_slack, + dataset_cache=dataset_cache, + filenames=filenames, + experimental_preloading=experimental_preloading, + num_train_files=num_train_files, + num_eval_files=num_eval_files, + use_pytorch_style_crop=True, + manifest_path=manifest_path) + + +def _decode_crop_and_flip(image_buffer, bbox, num_channels): + """Crops the given image to a random part of the image, and randomly flips. + + We use the fused decode_and_crop op, which performs better than the two ops + used separately in series, but note that this requires that the image be + passed in as an un-decoded string Tensor. + + Args: + image_buffer: scalar string Tensor representing the raw JPEG image buffer. + bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] + where each coordinate is [0, 1) and the coordinates are arranged as + [ymin, xmin, ymax, xmax]. + num_channels: Integer depth of the image buffer for decoding. + + Returns: + 3-D tensor with cropped image. + + """ + # A large fraction of image datasets contain a human-annotated bounding box + # delineating the region of the image containing the object of interest. We + # choose to create a new bounding box for the object which is a randomly + # distorted version of the human-annotated bounding box that obeys an + # allowed range of aspect ratios, sizes and overlap with the human-annotated + # bounding box. If no box is supplied, then we assume the bounding box is + # the entire image. + sample_distorted_bounding_box = tf.image.sample_distorted_bounding_box( + tf.image.extract_jpeg_shape(image_buffer), + bounding_boxes=bbox, + min_object_covered=0.1, + aspect_ratio_range=[0.75, 1.33], + area_range=[0.05, 1.0], + max_attempts=100, + use_image_if_no_bounding_boxes=True) + bbox_begin, bbox_size, _ = sample_distorted_bounding_box + + # Reassemble the bounding box in the format the crop op requires. + offset_y, offset_x, _ = tf.unstack(bbox_begin) + target_height, target_width, _ = tf.unstack(bbox_size) + crop_window = tf.stack([offset_y, offset_x, target_height, target_width]) + + # Use the fused decode and crop op here, which is faster than each in series. + cropped = tf.image.decode_and_crop_jpeg( + image_buffer, crop_window, channels=num_channels) + + # Flip to add a little more random distortion in. + cropped = tf.image.random_flip_left_right(cropped) + return cropped + + +def _central_crop(image, crop_height, crop_width): + """Performs central crops of the given image list. + + Args: + image: a 3-D image tensor + crop_height: the height of the image following the crop. + crop_width: the width of the image following the crop. + + Returns: + 3-D tensor with cropped image. + """ + shape = tf.shape(input=image) + height, width = shape[0], shape[1] + + amount_to_be_cropped_h = (height - crop_height) + crop_top = amount_to_be_cropped_h // 2 + amount_to_be_cropped_w = (width - crop_width) + crop_left = amount_to_be_cropped_w // 2 + return tf.slice( + image, [crop_top, crop_left, 0], [crop_height, crop_width, -1]) + + +def _mean_image_subtraction(image, means, num_channels): + """Subtracts the given means from each image channel. + + For example: + means = [123.68, 116.779, 103.939] + image = _mean_image_subtraction(image, means) + + Note that the rank of `image` must be known. + + Args: + image: a tensor of size [height, width, C]. + means: a C-vector of values to subtract from each channel. + num_channels: number of color channels in the image that will be distorted. + + Returns: + the centered image. + + Raises: + ValueError: If the rank of `image` is unknown, if `image` has a rank other + than three or if the number of channels in `image` doesn't match the + number of values in `means`. + """ + if image.get_shape().ndims != 3: + raise ValueError('Input must be of size [height, width, C>0]') + + if len(means) != num_channels: + raise ValueError('len(means) must match the number of channels') + + # We have a 1-D tensor of means; convert to 3-D. + # Note(b/130245863): we explicitly call `broadcast` instead of simply + # expanding dimensions for better performance. + means = tf.broadcast_to(means, tf.shape(image)) + + return image - means + + +def _smallest_size_at_least(height, width, resize_min): + """Computes new shape with the smallest side equal to `smallest_side`. + + Computes new shape with the smallest side equal to `smallest_side` while + preserving the original aspect ratio. + + Args: + height: an int32 scalar tensor indicating the current height. + width: an int32 scalar tensor indicating the current width. + resize_min: A python integer or scalar `Tensor` indicating the size of + the smallest side after resize. + + Returns: + new_height: an int32 scalar tensor indicating the new height. + new_width: an int32 scalar tensor indicating the new width. + """ + resize_min = tf.cast(resize_min, tf.float32) + + # Convert to floats to make subsequent calculations go smoothly. + height, width = tf.cast(height, tf.float32), tf.cast(width, tf.float32) + + smaller_dim = tf.minimum(height, width) + scale_ratio = resize_min / smaller_dim + + # Convert back to ints to make heights and widths that TF ops will accept. + new_height = tf.cast(height * scale_ratio, tf.int32) + new_width = tf.cast(width * scale_ratio, tf.int32) + + return new_height, new_width + + +def _aspect_preserving_resize(image, resize_min): + """Resize images preserving the original aspect ratio. + + Args: + image: A 3-D image `Tensor`. + resize_min: A python integer or scalar `Tensor` indicating the size of + the smallest side after resize. + + Returns: + resized_image: A 3-D tensor containing the resized image. + """ + shape = tf.shape(input=image) + height, width = shape[0], shape[1] + + new_height, new_width = _smallest_size_at_least(height, width, resize_min) + + return _resize_image(image, new_height, new_width) + + +def _resize_image(image, height, width): + """Simple wrapper around tf.resize_images. + + This is primarily to make sure we use the same `ResizeMethod` and other + details each time. + + Args: + image: A 3-D image `Tensor`. + height: The target height for the resized image. + width: The target width for the resized image. + + Returns: + resized_image: A 3-D tensor containing the resized image. The first two + dimensions have the shape [height, width]. + """ + return tf.compat.v1.image.resize( + image, [height, width], method=tf.image.ResizeMethod.BILINEAR, + align_corners=False) + + +def preprocess_image(image_buffer, bbox, output_height, output_width, + num_channels, is_training=False): + """Preprocesses the given image. + + Preprocessing includes decoding, cropping, and resizing for both training + and eval images. Training preprocessing, however, introduces some random + distortion of the image to improve accuracy. + + Args: + image_buffer: scalar string Tensor representing the raw JPEG image buffer. + bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] + where each coordinate is [0, 1) and the coordinates are arranged as + [ymin, xmin, ymax, xmax]. + output_height: The height of the image after preprocessing. + output_width: The width of the image after preprocessing. + num_channels: Integer depth of the image buffer for decoding. + is_training: `True` if we're preprocessing the image for training and + `False` otherwise. + + Returns: + A preprocessed image. + """ + if is_training: + # For training, we want to randomize some of the distortions. + image = _decode_crop_and_flip(image_buffer, bbox, num_channels) + image = _resize_image(image, output_height, output_width) + else: + # For validation, we want to decode, resize, then just crop the middle. + image = tf.image.decode_jpeg(image_buffer, channels=num_channels) + image = _aspect_preserving_resize(image, _RESIZE_MIN) + image = _central_crop(image, output_height, output_width) + + image.set_shape([output_height, output_width, num_channels]) + + return _mean_image_subtraction(image, CHANNEL_MEANS, num_channels) \ No newline at end of file diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/__init__.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/__init__.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/_base.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..9de1bbb93b2a45e8967e56ddbe40ffe86b371fcb --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/_base.py @@ -0,0 +1,168 @@ +# Copyright 2018 The TensorFlow Authors. 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. +# ============================================================================== +"""Flags which will be nearly universal across models.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from absl import flags +import tensorflow as tf + +from TensorFlow.utils.flags._conventions import help_wrap +from TensorFlow.utils.logs import hooks_helper + + +def define_base(data_dir=True, model_dir=True, clean=False, train_epochs=False, + epochs_between_evals=False, stop_threshold=False, + batch_size=True, num_gpu=False, hooks=False, export_dir=False, + distribution_strategy=False, run_eagerly=False): + """Register base flags. + + Args: + data_dir: Create a flag for specifying the input data directory. + model_dir: Create a flag for specifying the model file directory. + clean: Create a flag for removing the model_dir. + train_epochs: Create a flag to specify the number of training epochs. + epochs_between_evals: Create a flag to specify the frequency of testing. + stop_threshold: Create a flag to specify a threshold accuracy or other + eval metric which should trigger the end of training. + batch_size: Create a flag to specify the batch size. + num_gpu: Create a flag to specify the number of GPUs used. + hooks: Create a flag to specify hooks for logging. + export_dir: Create a flag to specify where a SavedModel should be exported. + distribution_strategy: Create a flag to specify which Distribution Strategy + to use. + run_eagerly: Create a flag to specify to run eagerly op by op. + Returns: + A list of flags for core.py to marks as key flags. + """ + key_flags = [] + + if data_dir: + flags.DEFINE_string( + name="data_dir", short_name="dd", default="/tmp", + help=help_wrap("The location of the input data.")) + key_flags.append("data_dir") + + flags.DEFINE_string( + name="jpeg_data_dir", short_name="jpdd", default=None, + help=help_wrap("The location of the JPEG version of the input data. Used for media dataloader")) + key_flags.append("jpeg_data_dir") + + if model_dir: + flags.DEFINE_string( + name="model_dir", short_name="md", default="/tmp", + help=help_wrap("The location of the model checkpoint files.")) + key_flags.append("model_dir") + + if clean: + flags.DEFINE_boolean( + name="clean", default=False, + help=help_wrap("If set, model_dir will be removed if it exists.")) + key_flags.append("clean") + + if train_epochs: + flags.DEFINE_integer( + name="train_epochs", short_name="te", default=1, + help=help_wrap("The number of epochs used to train.")) + key_flags.append("train_epochs") + + if epochs_between_evals: + flags.DEFINE_integer( + name="epochs_between_evals", short_name="ebe", default=1, + help=help_wrap("The number of training epochs to run between " + "evaluations.")) + key_flags.append("epochs_between_evals") + + if stop_threshold: + flags.DEFINE_float( + name="stop_threshold", short_name="st", + default=None, + help=help_wrap("If passed, training will stop at the earlier of " + "train_epochs and when the evaluation metric is " + "greater than or equal to stop_threshold.")) + + if batch_size: + flags.DEFINE_integer( + name="batch_size", short_name="bs", default=32, + help=help_wrap("Batch size for training and evaluation. When using " + "multiple gpus, this is the global batch size for " + "all devices. For example, if the batch size is 32 " + "and there are 4 GPUs, each GPU will get 8 examples on " + "each step.")) + key_flags.append("batch_size") + + if num_gpu: + flags.DEFINE_integer( + name="num_gpus", short_name="ng", + default=1, + help=help_wrap( + "How many GPUs to use at each worker with the " + "DistributionStrategies API. The default is 1.")) + + if run_eagerly: + flags.DEFINE_boolean( + name="run_eagerly", default=False, + help="Run the model op by op without building a model function.") + + if hooks: + # Construct a pretty summary of hooks. + hook_list_str = ( + u"\ufeff Hook:\n" + u"\n".join([u"\ufeff {}".format(key) for key + in hooks_helper.HOOKS])) + flags.DEFINE_list( + name="hooks", short_name="hk", default="LoggingTensorHook", + help=help_wrap( + u"A list of (case insensitive) strings to specify the names of " + u"training hooks.\n{}\n\ufeff Example: `--hooks ProfilerHook," + u"ExamplesPerSecondHook`\n See official.utils.logs.hooks_helper " + u"for details.".format(hook_list_str)) + ) + key_flags.append("hooks") + + if export_dir: + flags.DEFINE_string( + name="export_dir", short_name="ed", default=None, + help=help_wrap("If set, a SavedModel serialization of the model will " + "be exported to this directory at the end of training. " + "See the README for more details and relevant links.") + ) + key_flags.append("export_dir") + + if distribution_strategy: + flags.DEFINE_string( + name="distribution_strategy", short_name="ds", default="mirrored", + help=help_wrap("The Distribution Strategy to use for training. " + "Accepted values are 'off', 'one_device', " + "'mirrored', 'parameter_server', 'collective', " + "case insensitive. 'off' means not to use " + "Distribution Strategy; 'default' means to choose " + "from `MirroredStrategy` or `OneDeviceStrategy` " + "according to the number of GPUs.") + ) + + + return key_flags + + +def get_num_gpus(flags_obj): + """Treat num_gpus=-1 as 'use all'.""" + if flags_obj.num_gpus != -1: + return flags_obj.num_gpus + + from tensorflow.python.client import device_lib # pylint: disable=g-import-not-at-top + local_device_protos = device_lib.list_local_devices() + return sum([1 for d in local_device_protos if d.device_type == "GPU"]) diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/_benchmark.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..492128647ea080dff12a6036aecc2979460958fd --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/_benchmark.py @@ -0,0 +1,109 @@ +# Copyright 2018 The TensorFlow Authors. 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. +# ============================================================================== +"""Flags for benchmarking models.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from absl import flags + +from TensorFlow.utils.flags._conventions import help_wrap + + +def define_log_steps(): + flags.DEFINE_integer( + name="log_steps", default=100, + help="Frequency with which to log timing information with TimeHistory.") + + return [] + + +def define_benchmark(benchmark_log_dir=True, bigquery_uploader=True): + """Register benchmarking flags. + + Args: + benchmark_log_dir: Create a flag to specify location for benchmark logging. + bigquery_uploader: Create flags for uploading results to BigQuery. + + Returns: + A list of flags for core.py to marks as key flags. + """ + + key_flags = [] + + flags.DEFINE_enum( + name="benchmark_logger_type", default="BaseBenchmarkLogger", + enum_values=["BaseBenchmarkLogger", "BenchmarkFileLogger", + "BenchmarkBigQueryLogger"], + help=help_wrap("The type of benchmark logger to use. Defaults to using " + "BaseBenchmarkLogger which logs to STDOUT. Different " + "loggers will require other flags to be able to work.")) + flags.DEFINE_string( + name="benchmark_test_id", short_name="bti", default=None, + help=help_wrap("The unique test ID of the benchmark run. It could be the " + "combination of key parameters. It is hardware " + "independent and could be used compare the performance " + "between different test runs. This flag is designed for " + "human consumption, and does not have any impact within " + "the system.")) + + define_log_steps() + + if benchmark_log_dir: + flags.DEFINE_string( + name="benchmark_log_dir", short_name="bld", default=None, + help=help_wrap("The location of the benchmark logging.") + ) + + if bigquery_uploader: + flags.DEFINE_string( + name="gcp_project", short_name="gp", default=None, + help=help_wrap( + "The GCP project name where the benchmark will be uploaded.")) + + flags.DEFINE_string( + name="bigquery_data_set", short_name="bds", default="test_benchmark", + help=help_wrap( + "The Bigquery dataset name where the benchmark will be uploaded.")) + + flags.DEFINE_string( + name="bigquery_run_table", short_name="brt", default="benchmark_run", + help=help_wrap("The Bigquery table name where the benchmark run " + "information will be uploaded.")) + + flags.DEFINE_string( + name="bigquery_run_status_table", short_name="brst", + default="benchmark_run_status", + help=help_wrap("The Bigquery table name where the benchmark run " + "status information will be uploaded.")) + + flags.DEFINE_string( + name="bigquery_metric_table", short_name="bmt", + default="benchmark_metric", + help=help_wrap("The Bigquery table name where the benchmark metric " + "information will be uploaded.")) + + @flags.multi_flags_validator( + ["benchmark_logger_type", "benchmark_log_dir"], + message="--benchmark_logger_type=BenchmarkFileLogger will require " + "--benchmark_log_dir being set") + def _check_benchmark_log_dir(flags_dict): + benchmark_logger_type = flags_dict["benchmark_logger_type"] + if benchmark_logger_type == "BenchmarkFileLogger": + return flags_dict["benchmark_log_dir"] + return True + + return key_flags diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/_conventions.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/_conventions.py new file mode 100644 index 0000000000000000000000000000000000000000..81ad21b0c4c9a58fb7aa40402ae91c62a4c51352 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/_conventions.py @@ -0,0 +1,54 @@ +# Copyright 2018 The TensorFlow Authors. 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. +# ============================================================================== +"""Central location for shared argparse convention definitions.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import sys +import codecs +import functools + +from absl import app as absl_app +from absl import flags + + +# This codifies help string conventions and makes it easy to update them if +# necessary. Currently the only major effect is that help bodies start on the +# line after flags are listed. All flag definitions should wrap the text bodies +# with help wrap when calling DEFINE_*. +_help_wrap = functools.partial(flags.text_wrap, length=80, indent="", + firstline_indent="\n") + + +# Pretty formatting causes issues when utf-8 is not installed on a system. +def _stdout_utf8(): + try: + codecs.lookup("utf-8") + except LookupError: + return False + return sys.stdout.encoding == "UTF-8" + + +if _stdout_utf8(): + help_wrap = _help_wrap +else: + def help_wrap(text, *args, **kwargs): + return _help_wrap(text, *args, **kwargs).replace(u"\ufeff", u"") + + +# Replace None with h to also allow -h +absl_app.HelpshortFlag.SHORT_NAME = "h" diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/_device.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/_device.py new file mode 100644 index 0000000000000000000000000000000000000000..e91a09a3dbba2c9a2dd9bc9f5045f00cd12902d7 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/_device.py @@ -0,0 +1,85 @@ +# Copyright 2018 The TensorFlow Authors. 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. +# ============================================================================== +"""Flags for managing compute devices. Currently only contains TPU flags.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from absl import flags +import tensorflow as tf + +from TensorFlow.utils.flags._conventions import help_wrap + + +def require_cloud_storage(flag_names): + """Register a validator to check directory flags. + Args: + flag_names: An iterable of strings containing the names of flags to be + checked. + """ + msg = "TPU requires GCS path for {}".format(", ".join(flag_names)) + @flags.multi_flags_validator(["tpu"] + flag_names, message=msg) + def _path_check(flag_values): # pylint: disable=missing-docstring + if flag_values["tpu"] is None: + return True + + valid_flags = True + for key in flag_names: + if not flag_values[key].startswith("gs://"): + tf.compat.v1.logging.error("{} must be a GCS path.".format(key)) + valid_flags = False + + return valid_flags + + +def define_device(tpu=True): + """Register device specific flags. + Args: + tpu: Create flags to specify TPU operation. + Returns: + A list of flags for core.py to marks as key flags. + """ + + key_flags = [] + + if tpu: + flags.DEFINE_string( + name="tpu", default=None, + help=help_wrap( + "The Cloud TPU to use for training. This should be either the name " + "used when creating the Cloud TPU, or a " + "grpc://ip.address.of.tpu:8470 url. Passing `local` will use the" + "CPU of the local instance instead. (Good for debugging.)")) + key_flags.append("tpu") + + flags.DEFINE_string( + name="tpu_zone", default=None, + help=help_wrap( + "[Optional] GCE zone where the Cloud TPU is located in. If not " + "specified, we will attempt to automatically detect the GCE " + "project from metadata.")) + + flags.DEFINE_string( + name="tpu_gcp_project", default=None, + help=help_wrap( + "[Optional] Project name for the Cloud TPU-enabled project. If not " + "specified, we will attempt to automatically detect the GCE " + "project from metadata.")) + + flags.DEFINE_integer(name="num_tpu_shards", default=8, + help=help_wrap("Number of shards (TPU chips).")) + + return key_flags diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/_distribution.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/_distribution.py new file mode 100644 index 0000000000000000000000000000000000000000..d96140c7c3d4590fd4003b4695904353a284ba94 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/_distribution.py @@ -0,0 +1,54 @@ +# Copyright 2019 The TensorFlow Authors. 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. +# ============================================================================== +"""Flags related to distributed execution.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from absl import flags +import tensorflow as tf + +from TensorFlow.utils.flags._conventions import help_wrap + + +def define_distribution(worker_hosts=True, task_index=True): + """Register distributed execution flags. + + Args: + worker_hosts: Create a flag for specifying comma-separated list of workers. + task_index: Create a flag for specifying index of task. + + Returns: + A list of flags for core.py to marks as key flags. + """ + key_flags = [] + + if worker_hosts: + flags.DEFINE_string( + name='worker_hosts', default=None, + help=help_wrap( + 'Comma-separated list of worker ip:port pairs for running ' + 'multi-worker models with DistributionStrategy. The user would ' + 'start the program on each host with identical value for this ' + 'flag.')) + + if task_index: + flags.DEFINE_integer( + name='task_index', default=-1, + help=help_wrap('If multi-worker training, the task_index of this ' + 'worker.')) + + return key_flags diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/_misc.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..8dc49b436a5ac35e190e9f8ced8039cce6cd521c --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/_misc.py @@ -0,0 +1,50 @@ +# Copyright 2018 The TensorFlow Authors. 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. +# ============================================================================== +"""Misc flags.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from absl import flags + +from TensorFlow.utils.flags._conventions import help_wrap + + +def define_image(data_format=True): + """Register image specific flags. + + Args: + data_format: Create a flag to specify image axis convention. + + Returns: + A list of flags for core.py to marks as key flags. + """ + + key_flags = [] + + if data_format: + flags.DEFINE_enum( + name="data_format", short_name="df", default=None, + enum_values=["channels_first", "channels_last"], + help=help_wrap( + "A flag to override the data format used in the model. " + "channels_first provides a performance boost on GPU but is not " + "always compatible with CPU. If left unspecified, the data format " + "will be chosen automatically based on whether TensorFlow was " + "built for CPU or GPU.")) + key_flags.append("data_format") + + return key_flags diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/_performance.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/_performance.py new file mode 100644 index 0000000000000000000000000000000000000000..fe83e9432286f82cc5d9fe1dea2ac77d12af32c1 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/_performance.py @@ -0,0 +1,289 @@ +# Copyright 2018 The TensorFlow Authors. 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. +# ============================================================================== +"""Register flags for optimizing performance.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import multiprocessing + +from absl import flags # pylint: disable=g-bad-import-order +import tensorflow as tf # pylint: disable=g-bad-import-order + +from TensorFlow.utils.flags._conventions import help_wrap + + +# Map string to TensorFlow dtype +DTYPE_MAP = { + "fp16": tf.float16, + "bf16": tf.bfloat16, + "fp32": tf.float32, +} + + +def get_tf_dtype(flags_obj): + if getattr(flags_obj, "fp16_implementation", None) == "graph_rewrite": + # If the graph_rewrite is used, we build the graph with fp32, and let the + # graph rewrite change ops to fp16. + return tf.float32 + return DTYPE_MAP[flags_obj.dtype] + + +def get_loss_scale(flags_obj, default_for_fp16): + dtype = get_tf_dtype(flags_obj) + if flags_obj.loss_scale == "dynamic": + return flags_obj.loss_scale + elif flags_obj.loss_scale is not None: + return float(flags_obj.loss_scale) + elif dtype == tf.float32 or dtype == tf.bfloat16: + return 1 # No loss scaling is needed for fp32 + else: + assert dtype == tf.float16 + return default_for_fp16 + + +def define_performance(num_parallel_calls=False, inter_op=False, intra_op=False, + synthetic_data=False, max_train_steps=False, dtype=False, + all_reduce_alg=False, num_packs=False, + tf_gpu_thread_mode=False, + datasets_num_private_threads=False, + datasets_num_parallel_batches=False, + dynamic_loss_scale=False, fp16_implementation=False, + loss_scale=False, + tf_data_experimental_slack=False, enable_xla=False, + dataset_cache=True): + """Register flags for specifying performance tuning arguments. + + Args: + num_parallel_calls: Create a flag to specify parallelism of data loading. + inter_op: Create a flag to allow specification of inter op threads. + intra_op: Create a flag to allow specification of intra op threads. + synthetic_data: Create a flag to allow the use of synthetic data. + max_train_steps: Create a flags to allow specification of maximum number + of training steps + dtype: Create flags for specifying dtype. + all_reduce_alg: If set forces a specific algorithm for multi-gpu. + num_packs: If set provides number of packs for MirroredStrategy's cross + device ops. + tf_gpu_thread_mode: gpu_private triggers us of private thread pool. + datasets_num_private_threads: Number of private threads for datasets. + datasets_num_parallel_batches: Determines how many batches to process in + parallel when using map and batch from tf.data. + dynamic_loss_scale: Allow the "loss_scale" flag to take on the value + "dynamic". Only valid if `dtype` is True. + fp16_implementation: Create fp16_implementation flag. + loss_scale: Controls the loss scaling, normally for mixed-precision + training. Can only be turned on if dtype is also True. + tf_data_experimental_slack: Determines whether to enable tf.data's + `experimental_slack` option. + enable_xla: Determines if XLA (auto clustering) is turned on. + dataset_cache: Whether to cache the training and eval dataset on workers. + Typically used to improve training performance when training data is in + remote storage and can fit into worker memory. + + Returns: + A list of flags for core.py to marks as key flags. + """ + + key_flags = [] + if num_parallel_calls: + flags.DEFINE_integer( + name="num_parallel_calls", short_name="npc", + default=multiprocessing.cpu_count(), + help=help_wrap("The number of records that are processed in parallel " + "during input processing. This can be optimized per " + "data set but for generally homogeneous data sets, " + "should be approximately the number of available CPU " + "cores. (default behavior)")) + + if inter_op: + flags.DEFINE_integer( + name="inter_op_parallelism_threads", short_name="inter", default=0, + help=help_wrap("Number of inter_op_parallelism_threads to use for CPU. " + "See TensorFlow config.proto for details.") + ) + + if intra_op: + flags.DEFINE_integer( + name="intra_op_parallelism_threads", short_name="intra", default=0, + help=help_wrap("Number of intra_op_parallelism_threads to use for CPU. " + "See TensorFlow config.proto for details.")) + + if synthetic_data: + flags.DEFINE_bool( + name="use_synthetic_data", short_name="synth", default=False, + help=help_wrap( + "If set, use fake data (zeroes) instead of a real dataset. " + "This mode is useful for performance debugging, as it removes " + "input processing steps, but will not learn anything.")) + + if max_train_steps: + flags.DEFINE_integer( + name="max_train_steps", short_name="mts", default=None, help=help_wrap( + "The model will stop training if the global_step reaches this " + "value. If not set, training will run until the specified number " + "of epochs have run as usual. It is generally recommended to set " + "--train_epochs=1 when using this flag." + )) + + if dtype: + flags.DEFINE_enum( + name="dtype", short_name="dt", default="fp32", + enum_values=DTYPE_MAP.keys(), + help=help_wrap("The TensorFlow datatype used for calculations. " + "Variables may be cast to a higher precision on a " + "case-by-case basis for numerical stability.")) + + loss_scale_help_text = ( + "The amount to scale the loss by when the model is run. {}. Before " + "gradients are computed, the loss is multiplied by the loss scale, " + "making all gradients loss_scale times larger. To adjust for this, " + "gradients are divided by the loss scale before being applied to " + "variables. This is mathematically equivalent to training without " + "a loss scale, but the loss scale helps avoid some intermediate " + "gradients from underflowing to zero. If not provided the default " + "for fp16 is 128 and 1 for all other dtypes.{}" + ) + if dynamic_loss_scale: + loss_scale_help_text = loss_scale_help_text.format( + "This can be an int/float or the string 'dynamic'", + " The string 'dynamic' can be used to dynamically determine the " + "optimal loss scale during training, but currently this " + "significantly slows down performance") + loss_scale_validation_msg = ("loss_scale should be a positive int/float " + "or the string 'dynamic'.") + else: + loss_scale_help_text = loss_scale_help_text.format( + "This must be an int/float", "") + loss_scale_validation_msg = "loss_scale should be a positive int/float." + if loss_scale: + flags.DEFINE_string( + name="loss_scale", short_name="ls", default=None, + help=help_wrap(loss_scale_help_text)) + + @flags.validator(flag_name="loss_scale", + message=loss_scale_validation_msg) + def _check_loss_scale(loss_scale): # pylint: disable=unused-variable + """Validator to check the loss scale flag is valid.""" + if loss_scale is None: + return True # null case is handled in get_loss_scale() + + if loss_scale == "dynamic" and dynamic_loss_scale: + return True + + try: + loss_scale = float(loss_scale) + except ValueError: + return False + + return loss_scale > 0 + + if fp16_implementation: + flags.DEFINE_enum( + name="fp16_implementation", default="keras", + enum_values=("keras', 'graph_rewrite"), + help=help_wrap( + "When --dtype=fp16, how fp16 should be implemented. This has no " + "impact on correctness. 'keras' uses the " + "tf.keras.mixed_precision API. 'graph_rewrite' uses the " + "tf.compat.v1.mixed_precision.enable_mixed_precision_graph_rewrite " + "API.")) + + @flags.multi_flags_validator(["fp16_implementation", "dtype", + "loss_scale"]) + def _check_fp16_implementation(flags_dict): + """Validator to check fp16_implementation flag is valid.""" + if (flags_dict["fp16_implementation"] == "graph_rewrite" and + flags_dict["dtype"] != "fp16"): + raise flags.ValidationError("--fp16_implementation should not be " + "specified unless --dtype=fp16") + return True + + if all_reduce_alg: + flags.DEFINE_string( + name="all_reduce_alg", short_name="ara", default=None, + help=help_wrap("Defines the algorithm to use for performing all-reduce." + "When specified with MirroredStrategy for single " + "worker, this controls " + "tf.contrib.distribute.AllReduceCrossTowerOps. When " + "specified with MultiWorkerMirroredStrategy, this " + "controls " + "tf.distribute.experimental.CollectiveCommunication; " + "valid options are `ring` and `nccl`.")) + + if num_packs: + flags.DEFINE_integer( + name="num_packs", default=1, + help=help_wrap("Sets `num_packs` in the cross device ops used in " + "MirroredStrategy. For details, see " + "tf.distribute.NcclAllReduce.")) + + if tf_gpu_thread_mode: + flags.DEFINE_string( + name="tf_gpu_thread_mode", short_name="gt_mode", default=None, + help=help_wrap( + "Whether and how the GPU device uses its own threadpool.") + ) + + flags.DEFINE_integer( + name="per_gpu_thread_count", short_name="pgtc", default=0, + help=help_wrap( + "The number of threads to use for GPU. Only valid when " + "tf_gpu_thread_mode is not global.") + ) + + if datasets_num_private_threads: + flags.DEFINE_integer( + name="datasets_num_private_threads", + default=None, + help=help_wrap( + "Number of threads for a private threadpool created for all" + "datasets computation..") + ) + + if datasets_num_parallel_batches: + flags.DEFINE_integer( + name="datasets_num_parallel_batches", + default=None, + help=help_wrap( + "Determines how many batches to process in parallel when using " + "map and batch from tf.data.") + ) + + if dataset_cache: + flags.DEFINE_boolean( + name="dataset_cache", + default=True, + help=help_wrap( + "Determines whether to cache the training and eval dataset on workers. " + "Typically used to improve training performance when training and eval " + "data is in remote storage and can fit into worker memory.") + ) + + if tf_data_experimental_slack: + flags.DEFINE_boolean( + name="tf_data_experimental_slack", + default=False, + help=help_wrap( + "Whether to enable tf.data's `experimental_slack` option.") + ) + + if enable_xla: + flags.DEFINE_boolean( + name="enable_xla", default=False, + help="Whether to enable XLA auto jit compilation") + + return key_flags diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/core.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/core.py new file mode 100644 index 0000000000000000000000000000000000000000..35404f2c39f0a03a4095749af55cdd277cbfdfde --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/flags/core.py @@ -0,0 +1,133 @@ +# Copyright 2018 The TensorFlow Authors. 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. +# ============================================================================== +"""Public interface for flag definition. + +See _example.py for detailed instructions on defining flags. +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import sys +from six.moves import shlex_quote + +from absl import app as absl_app +from absl import flags + +from TensorFlow.utils.flags import _base +from TensorFlow.utils.flags import _benchmark +from TensorFlow.utils.flags import _conventions +from TensorFlow.utils.flags import _device +from TensorFlow.utils.flags import _distribution +from TensorFlow.utils.flags import _misc +from TensorFlow.utils.flags import _performance + + +def set_defaults(**kwargs): + for key, value in kwargs.items(): + flags.FLAGS.set_default(name=key, value=value) + + +def parse_flags(argv=None): + """Reset flags and reparse. Currently only used in testing.""" + flags.FLAGS.unparse_flags() + absl_app.parse_flags_with_usage(argv or sys.argv) + + +def register_key_flags_in_core(f): + """Defines a function in core.py, and registers its key flags. + + absl uses the location of a flags.declare_key_flag() to determine the context + in which a flag is key. By making all declares in core, this allows model + main functions to call flags.adopt_module_key_flags() on core and correctly + chain key flags. + + Args: + f: The function to be wrapped + + Returns: + The "core-defined" version of the input function. + """ + + def core_fn(*args, **kwargs): + key_flags = f(*args, **kwargs) + [flags.declare_key_flag(fl) for fl in key_flags] # pylint: disable=expression-not-assigned + return core_fn + + +define_base = register_key_flags_in_core(_base.define_base) +# We have define_base_eager for compatibility, since it used to be a separate +# function from define_base. +define_base_eager = define_base +define_log_steps = register_key_flags_in_core(_benchmark.define_log_steps) +define_benchmark = register_key_flags_in_core(_benchmark.define_benchmark) +define_device = register_key_flags_in_core(_device.define_device) +define_image = register_key_flags_in_core(_misc.define_image) +define_performance = register_key_flags_in_core(_performance.define_performance) +define_distribution = register_key_flags_in_core( + _distribution.define_distribution) + + +help_wrap = _conventions.help_wrap + + +get_num_gpus = _base.get_num_gpus +get_tf_dtype = _performance.get_tf_dtype +get_loss_scale = _performance.get_loss_scale +DTYPE_MAP = _performance.DTYPE_MAP +require_cloud_storage = _device.require_cloud_storage + +def _get_nondefault_flags_as_dict(): + """Returns the nondefault flags as a dict from flag name to value.""" + nondefault_flags = {} + for flag_name in flags.FLAGS: + flag_value = getattr(flags.FLAGS, flag_name) + if (flag_name != flags.FLAGS[flag_name].short_name and + flag_value != flags.FLAGS[flag_name].default): + nondefault_flags[flag_name] = flag_value + return nondefault_flags + + +def get_nondefault_flags_as_str(): + """Returns flags as a string that can be passed as command line arguments. + + E.g., returns: "--batch_size=256 --use_synthetic_data" for the following code + block: + + ``` + flags.FLAGS.batch_size = 256 + flags.FLAGS.use_synthetic_data = True + print(get_nondefault_flags_as_str()) + ``` + + Only flags with nondefault values are returned, as passing default flags as + command line arguments has no effect. + + Returns: + A string with the flags, that can be passed as command line arguments to a + program to use the flags. + """ + nondefault_flags = _get_nondefault_flags_as_dict() + flag_strings = [] + for name, value in sorted(nondefault_flags.items()): + if isinstance(value, bool): + flag_str = '--{}'.format(name) if value else '--no{}'.format(name) + elif isinstance(value, list): + flag_str = '--{}={}'.format(name, ','.join(value)) + else: + flag_str = '--{}={}'.format(name, value) + flag_strings.append(flag_str) + return ' '.join(shlex_quote(flag_str) for flag_str in flag_strings) diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/logs/__init__.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/logs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/logs/cloud_lib.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/logs/cloud_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..a2d9bd3dba813ae4f7a86e66fe74be27d24c53c6 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/logs/cloud_lib.py @@ -0,0 +1,34 @@ +# Copyright 2018 The TensorFlow Authors. 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. +# ============================================================================== + +"""Utilities that interact with cloud service. +""" + +import requests + +GCP_METADATA_URL = "http://metadata/computeMetadata/v1/instance/hostname" +GCP_METADATA_HEADER = {"Metadata-Flavor": "Google"} + + +def on_gcp(): + """Detect whether the current running environment is on GCP.""" + try: + # Timeout in 5 seconds, in case the test environment has connectivity issue. + # There is not default timeout, which means it might block forever. + response = requests.get( + GCP_METADATA_URL, headers=GCP_METADATA_HEADER, timeout=5) + return response.status_code == 200 + except requests.exceptions.RequestException: + return False diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/logs/hooks.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/logs/hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..2c9e4d6c55ec363d512710bdb54772a966c66fec --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/logs/hooks.py @@ -0,0 +1,130 @@ +# Copyright 2017 The TensorFlow Authors. 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. +# ============================================================================== + +"""Hook that counts examples per second every N steps or seconds.""" + + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import tensorflow as tf # pylint: disable=g-bad-import-order + +from TensorFlow.utils.logs import logger + + +class ExamplesPerSecondHook(tf.estimator.SessionRunHook): + """Hook to print out examples per second. + + Total time is tracked and then divided by the total number of steps + to get the average step time and then batch_size is used to determine + the running average of examples per second. The examples per second for the + most recent interval is also logged. + """ + + def __init__(self, + batch_size, + every_n_steps=None, + every_n_secs=None, + warm_steps=0, + metric_logger=None): + """Initializer for ExamplesPerSecondHook. + + Args: + batch_size: Total batch size across all workers used to calculate + examples/second from global time. + every_n_steps: Log stats every n steps. + every_n_secs: Log stats every n seconds. Exactly one of the + `every_n_steps` or `every_n_secs` should be set. + warm_steps: The number of steps to be skipped before logging and running + average calculation. warm_steps steps refers to global steps across all + workers, not on each worker + metric_logger: instance of `BenchmarkLogger`, the benchmark logger that + hook should use to write the log. If None, BaseBenchmarkLogger will + be used. + + Raises: + ValueError: if neither `every_n_steps` or `every_n_secs` is set, or + both are set. + """ + + if (every_n_steps is None) == (every_n_secs is None): + raise ValueError("exactly one of every_n_steps" + " and every_n_secs should be provided.") + + self._logger = metric_logger or logger.BaseBenchmarkLogger() + + self._timer = tf.estimator.SecondOrStepTimer( + every_steps=every_n_steps, every_secs=every_n_secs) + + self._step_train_time = 0 + self._total_steps = 0 + self._batch_size = batch_size + self._warm_steps = warm_steps + # List of examples per second logged every_n_steps. + self.current_examples_per_sec_list = [] + + def begin(self): + """Called once before using the session to check global step.""" + self._global_step_tensor = tf.compat.v1.train.get_global_step() + if self._global_step_tensor is None: + raise RuntimeError( + "Global step should be created to use StepCounterHook.") + + def before_run(self, run_context): # pylint: disable=unused-argument + """Called before each call to run(). + + Args: + run_context: A SessionRunContext object. + + Returns: + A SessionRunArgs object or None if never triggered. + """ + return tf.estimator.SessionRunArgs(self._global_step_tensor) + + def after_run(self, run_context, run_values): # pylint: disable=unused-argument + """Called after each call to run(). + + Args: + run_context: A SessionRunContext object. + run_values: A SessionRunValues object. + """ + global_step = run_values.results + + if self._timer.should_trigger_for_step( + global_step) and global_step > self._warm_steps: + elapsed_time, elapsed_steps = self._timer.update_last_triggered_step( + global_step) + if elapsed_time is not None: + self._step_train_time += elapsed_time + self._total_steps += elapsed_steps + + # average examples per second is based on the total (accumulative) + # training steps and training time so far + average_examples_per_sec = self._batch_size * ( + self._total_steps / self._step_train_time) + # current examples per second is based on the elapsed training steps + # and training time per batch + current_examples_per_sec = self._batch_size * ( + elapsed_steps / elapsed_time) + # Logs entries to be read from hook during or after run. + self.current_examples_per_sec_list.append(current_examples_per_sec) + self._logger.log_metric( + "average_examples_per_sec", average_examples_per_sec, + global_step=global_step) + + self._logger.log_metric( + "current_examples_per_sec", current_examples_per_sec, + global_step=global_step) diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/logs/hooks_helper.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/logs/hooks_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..dcc9b8279f7b68fadcd51a5efa6778c773734ec6 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/logs/hooks_helper.py @@ -0,0 +1,172 @@ +# Copyright 2017 The TensorFlow Authors. 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. +# ============================================================================== + +"""Hooks helper to return a list of TensorFlow hooks for training by name. + +More hooks can be added to this set. To add a new hook, 1) add the new hook to +the registry in HOOKS, 2) add a corresponding function that parses out necessary +parameters. +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import tensorflow as tf # pylint: disable=g-bad-import-order + +from TensorFlow.utils.logs import hooks +from TensorFlow.utils.logs import logger +from TensorFlow.utils.logs import metric_hook + +_TENSORS_TO_LOG = dict((x, x) for x in ['learning_rate', + 'cross_entropy', + 'train_accuracy']) + + +def get_train_hooks(name_list, use_tpu=False, **kwargs): + """Factory for getting a list of TensorFlow hooks for training by name. + + Args: + name_list: a list of strings to name desired hook classes. Allowed: + LoggingTensorHook, ProfilerHook, ExamplesPerSecondHook, which are defined + as keys in HOOKS + use_tpu: Boolean of whether computation occurs on a TPU. This will disable + hooks altogether. + **kwargs: a dictionary of arguments to the hooks. + + Returns: + list of instantiated hooks, ready to be used in a classifier.train call. + + Raises: + ValueError: if an unrecognized name is passed. + """ + + if not name_list: + return [] + + if use_tpu: + tf.compat.v1.logging.warning('hooks_helper received name_list `{}`, but a ' + 'TPU is specified. No hooks will be used.' + .format(name_list)) + return [] + + train_hooks = [] + for name in name_list: + hook_name = HOOKS.get(name.strip().lower()) + if hook_name is None: + raise ValueError('Unrecognized training hook requested: {}'.format(name)) + else: + train_hooks.append(hook_name(**kwargs)) + + return train_hooks + + +def get_logging_tensor_hook(every_n_iter=100, tensors_to_log=None, **kwargs): # pylint: disable=unused-argument + """Function to get LoggingTensorHook. + + Args: + every_n_iter: `int`, print the values of `tensors` once every N local + steps taken on the current worker. + tensors_to_log: List of tensor names or dictionary mapping labels to tensor + names. If not set, log _TENSORS_TO_LOG by default. + **kwargs: a dictionary of arguments to LoggingTensorHook. + + Returns: + Returns a LoggingTensorHook with a standard set of tensors that will be + printed to stdout. + """ + if tensors_to_log is None: + tensors_to_log = _TENSORS_TO_LOG + + return tf.estimator.LoggingTensorHook( + tensors=tensors_to_log, + every_n_iter=every_n_iter) + + +def get_profiler_hook(model_dir, save_steps=1000, **kwargs): # pylint: disable=unused-argument + """Function to get ProfilerHook. + + Args: + model_dir: The directory to save the profile traces to. + save_steps: `int`, print profile traces every N steps. + **kwargs: a dictionary of arguments to ProfilerHook. + + Returns: + Returns a ProfilerHook that writes out timelines that can be loaded into + profiling tools like chrome://tracing. + """ + return tf.estimator.ProfilerHook(save_steps=save_steps, output_dir=model_dir) + + +def get_examples_per_second_hook(every_n_steps=100, + batch_size=128, + warm_steps=5, + **kwargs): # pylint: disable=unused-argument + """Function to get ExamplesPerSecondHook. + + Args: + every_n_steps: `int`, print current and average examples per second every + N steps. + batch_size: `int`, total batch size used to calculate examples/second from + global time. + warm_steps: skip this number of steps before logging and running average. + **kwargs: a dictionary of arguments to ExamplesPerSecondHook. + + Returns: + Returns a ProfilerHook that writes out timelines that can be loaded into + profiling tools like chrome://tracing. + """ + return hooks.ExamplesPerSecondHook( + batch_size=batch_size, every_n_steps=every_n_steps, + warm_steps=warm_steps, metric_logger=logger.get_benchmark_logger()) + + +def get_logging_metric_hook(tensors_to_log=None, + every_n_secs=600, + **kwargs): # pylint: disable=unused-argument + """Function to get LoggingMetricHook. + + Args: + tensors_to_log: List of tensor names or dictionary mapping labels to tensor + names. If not set, log _TENSORS_TO_LOG by default. + every_n_secs: `int`, the frequency for logging the metric. Default to every + 10 mins. + **kwargs: a dictionary of arguments. + + Returns: + Returns a LoggingMetricHook that saves tensor values in a JSON format. + """ + if tensors_to_log is None: + tensors_to_log = _TENSORS_TO_LOG + return metric_hook.LoggingMetricHook( + tensors=tensors_to_log, + metric_logger=logger.get_benchmark_logger(), + every_n_secs=every_n_secs) + + +def get_step_counter_hook(**kwargs): + """Function to get StepCounterHook.""" + del kwargs + return tf.estimator.StepCounterHook() + + +# A dictionary to map one hook name and its corresponding function +HOOKS = { + 'loggingtensorhook': get_logging_tensor_hook, + 'profilerhook': get_profiler_hook, + 'examplespersecondhook': get_examples_per_second_hook, + 'loggingmetrichook': get_logging_metric_hook, + 'stepcounterhook': get_step_counter_hook +} diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/logs/logger.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/logs/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..21c29272ccbeaae2c2b082e1a0108b9bf62e7e9c --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/logs/logger.py @@ -0,0 +1,423 @@ +# Copyright 2018 The TensorFlow Authors. 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. +# ============================================================================== + +"""Logging utilities for benchmark. + +For collecting local environment metrics like CPU and memory, certain python +packages need be installed. See README for details. +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import contextlib +import datetime +import json +import multiprocessing +import numbers +import os +import threading +import uuid + +from six.moves import _thread as thread +from absl import flags +import tensorflow as tf +from tensorflow.python.client import device_lib + +from TensorFlow.utils.logs import cloud_lib + +METRIC_LOG_FILE_NAME = "metric.log" +BENCHMARK_RUN_LOG_FILE_NAME = "benchmark_run.log" +_DATE_TIME_FORMAT_PATTERN = "%Y-%m-%dT%H:%M:%S.%fZ" +GCP_TEST_ENV = "GCP" +RUN_STATUS_SUCCESS = "success" +RUN_STATUS_FAILURE = "failure" +RUN_STATUS_RUNNING = "running" + + +FLAGS = flags.FLAGS + +# Don't use it directly. Use get_benchmark_logger to access a logger. +_benchmark_logger = None +_logger_lock = threading.Lock() + + +def config_benchmark_logger(flag_obj=None): + """Config the global benchmark logger.""" + _logger_lock.acquire() + try: + global _benchmark_logger + if not flag_obj: + flag_obj = FLAGS + + if (not hasattr(flag_obj, "benchmark_logger_type") or + flag_obj.benchmark_logger_type == "BaseBenchmarkLogger"): + _benchmark_logger = BaseBenchmarkLogger() + elif flag_obj.benchmark_logger_type == "BenchmarkFileLogger": + _benchmark_logger = BenchmarkFileLogger(flag_obj.benchmark_log_dir) + elif flag_obj.benchmark_logger_type == "BenchmarkBigQueryLogger": + from benchmark import benchmark_uploader as bu # pylint: disable=g-import-not-at-top + bq_uploader = bu.BigQueryUploader(gcp_project=flag_obj.gcp_project) + _benchmark_logger = BenchmarkBigQueryLogger( + bigquery_uploader=bq_uploader, + bigquery_data_set=flag_obj.bigquery_data_set, + bigquery_run_table=flag_obj.bigquery_run_table, + bigquery_run_status_table=flag_obj.bigquery_run_status_table, + bigquery_metric_table=flag_obj.bigquery_metric_table, + run_id=str(uuid.uuid4())) + else: + raise ValueError("Unrecognized benchmark_logger_type: %s" + % flag_obj.benchmark_logger_type) + + finally: + _logger_lock.release() + return _benchmark_logger + + +def get_benchmark_logger(): + if not _benchmark_logger: + config_benchmark_logger() + return _benchmark_logger + + +@contextlib.contextmanager +def benchmark_context(flag_obj): + """Context of benchmark, which will update status of the run accordingly.""" + benchmark_logger = config_benchmark_logger(flag_obj) + try: + yield + benchmark_logger.on_finish(RUN_STATUS_SUCCESS) + except Exception: # pylint: disable=broad-except + # Catch all the exception, update the run status to be failure, and re-raise + benchmark_logger.on_finish(RUN_STATUS_FAILURE) + raise + + +class BaseBenchmarkLogger(object): + """Class to log the benchmark information to STDOUT.""" + + def log_evaluation_result(self, eval_results): + """Log the evaluation result. + + The evaluate result is a dictionary that contains metrics defined in + model_fn. It also contains a entry for global_step which contains the value + of the global step when evaluation was performed. + + Args: + eval_results: dict, the result of evaluate. + """ + if not isinstance(eval_results, dict): + tf.compat.v1.logging.warning( + "eval_results should be dictionary for logging. Got %s", + type(eval_results)) + return + global_step = eval_results[tf.compat.v1.GraphKeys.GLOBAL_STEP] + for key in sorted(eval_results): + if key != tf.compat.v1.GraphKeys.GLOBAL_STEP: + self.log_metric(key, eval_results[key], global_step=global_step) + + def log_metric(self, name, value, unit=None, global_step=None, extras=None): + """Log the benchmark metric information to local file. + + Currently the logging is done in a synchronized way. This should be updated + to log asynchronously. + + Args: + name: string, the name of the metric to log. + value: number, the value of the metric. The value will not be logged if it + is not a number type. + unit: string, the unit of the metric, E.g "image per second". + global_step: int, the global_step when the metric is logged. + extras: map of string:string, the extra information about the metric. + """ + metric = _process_metric_to_json(name, value, unit, global_step, extras) + if metric: + tf.compat.v1.logging.info("Benchmark metric: %s", metric) + + def log_run_info(self, model_name, dataset_name, run_params, test_id=None): + tf.compat.v1.logging.info( + "Benchmark run: %s", _gather_run_info(model_name, dataset_name, + run_params, test_id)) + + def on_finish(self, status): + pass + + +class BenchmarkFileLogger(BaseBenchmarkLogger): + """Class to log the benchmark information to local disk.""" + + def __init__(self, logging_dir): + super(BenchmarkFileLogger, self).__init__() + self._logging_dir = logging_dir + if not tf.io.gfile.isdir(self._logging_dir): + tf.io.gfile.makedirs(self._logging_dir) + self._metric_file_handler = tf.io.gfile.GFile( + os.path.join(self._logging_dir, METRIC_LOG_FILE_NAME), "a") + + def log_metric(self, name, value, unit=None, global_step=None, extras=None): + """Log the benchmark metric information to local file. + + Currently the logging is done in a synchronized way. This should be updated + to log asynchronously. + + Args: + name: string, the name of the metric to log. + value: number, the value of the metric. The value will not be logged if it + is not a number type. + unit: string, the unit of the metric, E.g "image per second". + global_step: int, the global_step when the metric is logged. + extras: map of string:string, the extra information about the metric. + """ + metric = _process_metric_to_json(name, value, unit, global_step, extras) + if metric: + try: + json.dump(metric, self._metric_file_handler) + self._metric_file_handler.write("\n") + self._metric_file_handler.flush() + except (TypeError, ValueError) as e: + tf.compat.v1.logging.warning( + "Failed to dump metric to log file: name %s, value %s, error %s", + name, value, e) + + def log_run_info(self, model_name, dataset_name, run_params, test_id=None): + """Collect most of the TF runtime information for the local env. + + The schema of the run info follows official/benchmark/datastore/schema. + + Args: + model_name: string, the name of the model. + dataset_name: string, the name of dataset for training and evaluation. + run_params: dict, the dictionary of parameters for the run, it could + include hyperparameters or other params that are important for the run. + test_id: string, the unique name of the test run by the combination of key + parameters, eg batch size, num of GPU. It is hardware independent. + """ + run_info = _gather_run_info(model_name, dataset_name, run_params, test_id) + + with tf.io.gfile.GFile(os.path.join( + self._logging_dir, BENCHMARK_RUN_LOG_FILE_NAME), "w") as f: + try: + json.dump(run_info, f) + f.write("\n") + except (TypeError, ValueError) as e: + tf.compat.v1.logging.warning( + "Failed to dump benchmark run info to log file: %s", e) + + def on_finish(self, status): + self._metric_file_handler.flush() + self._metric_file_handler.close() + + +class BenchmarkBigQueryLogger(BaseBenchmarkLogger): + """Class to log the benchmark information to BigQuery data store.""" + + def __init__(self, + bigquery_uploader, + bigquery_data_set, + bigquery_run_table, + bigquery_run_status_table, + bigquery_metric_table, + run_id): + super(BenchmarkBigQueryLogger, self).__init__() + self._bigquery_uploader = bigquery_uploader + self._bigquery_data_set = bigquery_data_set + self._bigquery_run_table = bigquery_run_table + self._bigquery_run_status_table = bigquery_run_status_table + self._bigquery_metric_table = bigquery_metric_table + self._run_id = run_id + + def log_metric(self, name, value, unit=None, global_step=None, extras=None): + """Log the benchmark metric information to bigquery. + + Args: + name: string, the name of the metric to log. + value: number, the value of the metric. The value will not be logged if it + is not a number type. + unit: string, the unit of the metric, E.g "image per second". + global_step: int, the global_step when the metric is logged. + extras: map of string:string, the extra information about the metric. + """ + metric = _process_metric_to_json(name, value, unit, global_step, extras) + if metric: + # Starting new thread for bigquery upload in case it might take long time + # and impact the benchmark and performance measurement. Starting a new + # thread might have potential performance impact for model that run on + # CPU. + thread.start_new_thread( + self._bigquery_uploader.upload_benchmark_metric_json, + (self._bigquery_data_set, + self._bigquery_metric_table, + self._run_id, + [metric])) + + def log_run_info(self, model_name, dataset_name, run_params, test_id=None): + """Collect most of the TF runtime information for the local env. + + The schema of the run info follows official/benchmark/datastore/schema. + + Args: + model_name: string, the name of the model. + dataset_name: string, the name of dataset for training and evaluation. + run_params: dict, the dictionary of parameters for the run, it could + include hyperparameters or other params that are important for the run. + test_id: string, the unique name of the test run by the combination of key + parameters, eg batch size, num of GPU. It is hardware independent. + """ + run_info = _gather_run_info(model_name, dataset_name, run_params, test_id) + # Starting new thread for bigquery upload in case it might take long time + # and impact the benchmark and performance measurement. Starting a new + # thread might have potential performance impact for model that run on CPU. + thread.start_new_thread( + self._bigquery_uploader.upload_benchmark_run_json, + (self._bigquery_data_set, + self._bigquery_run_table, + self._run_id, + run_info)) + thread.start_new_thread( + self._bigquery_uploader.insert_run_status, + (self._bigquery_data_set, + self._bigquery_run_status_table, + self._run_id, + RUN_STATUS_RUNNING)) + + def on_finish(self, status): + self._bigquery_uploader.update_run_status( + self._bigquery_data_set, + self._bigquery_run_status_table, + self._run_id, + status) + + +def _gather_run_info(model_name, dataset_name, run_params, test_id): + """Collect the benchmark run information for the local environment.""" + run_info = { + "model_name": model_name, + "dataset": {"name": dataset_name}, + "machine_config": {}, + "test_id": test_id, + "run_date": datetime.datetime.utcnow().strftime( + _DATE_TIME_FORMAT_PATTERN)} + _collect_tensorflow_info(run_info) + _collect_tensorflow_environment_variables(run_info) + _collect_run_params(run_info, run_params) + _collect_cpu_info(run_info) + _collect_memory_info(run_info) + _collect_test_environment(run_info) + return run_info + + +def _process_metric_to_json( + name, value, unit=None, global_step=None, extras=None): + """Validate the metric data and generate JSON for insert.""" + if not isinstance(value, numbers.Number): + tf.compat.v1.logging.warning( + "Metric value to log should be a number. Got %s", type(value)) + return None + + extras = _convert_to_json_dict(extras) + return { + "name": name, + "value": float(value), + "unit": unit, + "global_step": global_step, + "timestamp": datetime.datetime.utcnow().strftime( + _DATE_TIME_FORMAT_PATTERN), + "extras": extras} + + +def _collect_tensorflow_info(run_info): + run_info["tensorflow_version"] = { + "version": tf.version.VERSION, "git_hash": tf.version.GIT_VERSION} + + +def _collect_run_params(run_info, run_params): + """Log the parameter information for the benchmark run.""" + def process_param(name, value): + type_check = { + str: {"name": name, "string_value": value}, + int: {"name": name, "long_value": value}, + bool: {"name": name, "bool_value": str(value)}, + float: {"name": name, "float_value": value}, + } + return type_check.get(type(value), + {"name": name, "string_value": str(value)}) + if run_params: + run_info["run_parameters"] = [ + process_param(k, v) for k, v in sorted(run_params.items())] + + +def _collect_tensorflow_environment_variables(run_info): + run_info["tensorflow_environment_variables"] = [ + {"name": k, "value": v} + for k, v in sorted(os.environ.items()) if k.startswith("TF_")] + + +# The following code is mirrored from tensorflow/tools/test/system_info_lib +# which is not exposed for import. +def _collect_cpu_info(run_info): + """Collect the CPU information for the local environment.""" + cpu_info = {} + + cpu_info["num_cores"] = multiprocessing.cpu_count() + + try: + # Note: cpuinfo is not installed in the TensorFlow OSS tree. + # It is installable via pip. + import cpuinfo # pylint: disable=g-import-not-at-top + + info = cpuinfo.get_cpu_info() + cpu_info["cpu_info"] = info["brand"] + cpu_info["mhz_per_cpu"] = info["hz_advertised_raw"][0] / 1.0e6 + + run_info["machine_config"]["cpu_info"] = cpu_info + except ImportError: + tf.compat.v1.logging.warn( + "'cpuinfo' not imported. CPU info will not be logged.") + + +def _collect_memory_info(run_info): + try: + # Note: psutil is not installed in the TensorFlow OSS tree. + # It is installable via pip. + import psutil # pylint: disable=g-import-not-at-top + vmem = psutil.virtual_memory() + run_info["machine_config"]["memory_total"] = vmem.total + run_info["machine_config"]["memory_available"] = vmem.available + except ImportError: + tf.compat.v1.logging.warn( + "'psutil' not imported. Memory info will not be logged.") + + +def _collect_test_environment(run_info): + """Detect the local environment, eg GCE, AWS or DGX, etc.""" + if cloud_lib.on_gcp(): + run_info["test_environment"] = GCP_TEST_ENV + # TODO(scottzhu): Add more testing env detection for other platform + + +def _parse_gpu_model(physical_device_desc): + # Assume all the GPU connected are same model + for kv in physical_device_desc.split(","): + k, _, v = kv.partition(":") + if k.strip() == "name": + return v.strip() + return None + + +def _convert_to_json_dict(input_dict): + if input_dict: + return [{"name": k, "value": v} for k, v in sorted(input_dict.items())] + else: + return [] diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/logs/metric_hook.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/logs/metric_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..f408e3e95f09bd48373564389f4c9f1c28f698a5 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/logs/metric_hook.py @@ -0,0 +1,97 @@ +# Copyright 2018 The TensorFlow Authors. 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. +# ============================================================================== +"""Session hook for logging benchmark metric.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import tensorflow as tf # pylint: disable=g-bad-import-order + + +class LoggingMetricHook(tf.estimator.LoggingTensorHook): + """Hook to log benchmark metric information. + + This hook is very similar as tf.train.LoggingTensorHook, which logs given + tensors every N local steps, every N seconds, or at the end. The metric + information will be logged to given log_dir or via metric_logger in JSON + format, which can be consumed by data analysis pipeline later. + + Note that if `at_end` is True, `tensors` should not include any tensor + whose evaluation produces a side effect such as consuming additional inputs. + """ + + def __init__(self, tensors, metric_logger=None, + every_n_iter=None, every_n_secs=None, at_end=False): + """Initializer for LoggingMetricHook. + + Args: + tensors: `dict` that maps string-valued tags to tensors/tensor names, + or `iterable` of tensors/tensor names. + metric_logger: instance of `BenchmarkLogger`, the benchmark logger that + hook should use to write the log. + every_n_iter: `int`, print the values of `tensors` once every N local + steps taken on the current worker. + every_n_secs: `int` or `float`, print the values of `tensors` once every N + seconds. Exactly one of `every_n_iter` and `every_n_secs` should be + provided. + at_end: `bool` specifying whether to print the values of `tensors` at the + end of the run. + + Raises: + ValueError: + 1. `every_n_iter` is non-positive, or + 2. Exactly one of every_n_iter and every_n_secs should be provided. + 3. Exactly one of log_dir and metric_logger should be provided. + """ + super(LoggingMetricHook, self).__init__( + tensors=tensors, + every_n_iter=every_n_iter, + every_n_secs=every_n_secs, + at_end=at_end) + + if metric_logger is None: + raise ValueError("metric_logger should be provided.") + self._logger = metric_logger + + def begin(self): + super(LoggingMetricHook, self).begin() + self._global_step_tensor = tf.compat.v1.train.get_global_step() + if self._global_step_tensor is None: + raise RuntimeError( + "Global step should be created to use LoggingMetricHook.") + if self._global_step_tensor.name not in self._current_tensors: + self._current_tensors[self._global_step_tensor.name] = ( + self._global_step_tensor) + + def after_run(self, unused_run_context, run_values): + # should_trigger is a internal state that populated at before_run, and it is + # using self_timer to determine whether it should trigger. + if self._should_trigger: + self._log_metric(run_values.results) + + self._iter_count += 1 + + def end(self, session): + if self._log_at_end: + values = session.run(self._current_tensors) + self._log_metric(values) + + def _log_metric(self, tensor_values): + self._timer.update_last_triggered_step(self._iter_count) + global_step = tensor_values[self._global_step_tensor.name] + # self._tag_order is populated during the init of LoggingTensorHook + for tag in self._tag_order: + self._logger.log_metric(tag, tensor_values[tag], global_step=global_step) diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/misc/__init__.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/misc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/misc/distribution_utils.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/misc/distribution_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a3d662f4bc9e499da119b348acefd642e4a0941f --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/misc/distribution_utils.py @@ -0,0 +1,346 @@ +# Copyright 2018 The TensorFlow Authors. 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. +# ============================================================================== +"""Helper functions for running models in a distributed setting.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import json +import os +import random +import string +import tensorflow.compat.v2 as tf + +from TensorFlow.utils.misc import tpu_lib + +from habana_frameworks.tensorflow.distribute import HPUStrategy + + +def _collective_communication(all_reduce_alg): + """Return a CollectiveCommunication based on all_reduce_alg. + + Args: + all_reduce_alg: a string specifying which collective communication to pick, + or None. + + Returns: + tf.distribute.experimental.CollectiveCommunication object + + Raises: + ValueError: if `all_reduce_alg` not in [None, 'ring', 'nccl'] + """ + collective_communication_options = { + None: tf.distribute.experimental.CollectiveCommunication.AUTO, + "ring": tf.distribute.experimental.CollectiveCommunication.RING, + "nccl": tf.distribute.experimental.CollectiveCommunication.NCCL + } + if all_reduce_alg not in collective_communication_options: + raise ValueError( + "When used with `multi_worker_mirrored`, valid values for " + "all_reduce_alg are ['ring', 'nccl']. Supplied value: {}".format( + all_reduce_alg)) + return collective_communication_options[all_reduce_alg] + + +def _mirrored_cross_device_ops(all_reduce_alg, num_packs): + """Return a CrossDeviceOps based on all_reduce_alg and num_packs. + + Args: + all_reduce_alg: a string specifying which cross device op to pick, or None. + num_packs: an integer specifying number of packs for the cross device op. + + Returns: + tf.distribute.CrossDeviceOps object or None. + + Raises: + ValueError: if `all_reduce_alg` not in [None, 'nccl', 'hierarchical_copy']. + """ + if all_reduce_alg is None: + return None + mirrored_all_reduce_options = { + "nccl": tf.distribute.NcclAllReduce, + "hierarchical_copy": tf.distribute.HierarchicalCopyAllReduce + } + if all_reduce_alg not in mirrored_all_reduce_options: + raise ValueError( + "When used with `mirrored`, valid values for all_reduce_alg are " + "['nccl', 'hierarchical_copy']. Supplied value: {}".format( + all_reduce_alg)) + cross_device_ops_class = mirrored_all_reduce_options[all_reduce_alg] + return cross_device_ops_class(num_packs=num_packs) + + +def get_distribution_strategy(distribution_strategy="mirrored", + num_gpus=0, + num_hpus=0, + all_reduce_alg=None, + num_packs=1, + tpu_address=None): + """Return a DistributionStrategy for running the model. + + Args: + distribution_strategy: a string specifying which distribution strategy to + use. Accepted values are 'off', 'one_device', 'mirrored', + 'parameter_server', 'multi_worker_mirrored', and 'tpu' -- case insensitive. + 'off' means not to use Distribution Strategy; 'tpu' means to use + TPUStrategy using `tpu_address`. + num_gpus: Number of GPUs to run this model. + all_reduce_alg: Optional. Specifies which algorithm to use when performing + all-reduce. For `MirroredStrategy`, valid values are "nccl" and + "hierarchical_copy". For `MultiWorkerMirroredStrategy`, valid values are + "ring" and "nccl". If None, DistributionStrategy will choose based on + device topology. + num_packs: Optional. Sets the `num_packs` in `tf.distribute.NcclAllReduce` + or `tf.distribute.HierarchicalCopyAllReduce` for `MirroredStrategy`. + tpu_address: Optional. String that represents TPU to connect to. Must not + be None if `distribution_strategy` is set to `tpu`. + Returns: + tf.distribute.DistibutionStrategy object. + Raises: + ValueError: if `distribution_strategy` is 'off' or 'one_device' and + `num_gpus` is larger than 1; or `num_gpus` is negative or if + `distribution_strategy` is `tpu` but `tpu_address` is not specified. + """ + if num_gpus < 0: + raise ValueError("`num_gpus` can not be negative.") + + distribution_strategy = distribution_strategy.lower() + if distribution_strategy == "off": + if num_gpus > 1: + raise ValueError( + "When {} GPUs are specified, distribution_strategy " + "flag cannot be set to 'off'.".format(num_gpus)) + return None + + if distribution_strategy == "hpu": + return HPUStrategy() + + if distribution_strategy == "tpu": + # When tpu_address is an empty string, we communicate with local TPUs. + cluster_resolver = tpu_lib.tpu_initialize(tpu_address) + return tf.distribute.experimental.TPUStrategy(cluster_resolver) + + if distribution_strategy == "multi_worker_mirrored": + return tf.distribute.experimental.MultiWorkerMirroredStrategy( + communication=_collective_communication(all_reduce_alg)) + + if distribution_strategy == "one_device": + if num_gpus == 0 and num_hpus == 0: + return tf.distribute.OneDeviceStrategy("device:CPU:0") + if num_hpus == 1: + return tf.distribute.OneDeviceStrategy("device:HPU:0") + if num_gpus > 1 or num_hpus > 1: + raise ValueError("`OneDeviceStrategy` can not be used for more than " + "one device.") + return tf.distribute.OneDeviceStrategy("device:GPU:0") + + if distribution_strategy == "mirrored": + if num_gpus == 0: + devices = ["device:CPU:0"] + else: + devices = ["device:GPU:%d" % i for i in range(num_gpus)] + return tf.distribute.MirroredStrategy( + devices=devices, + cross_device_ops=_mirrored_cross_device_ops(all_reduce_alg, num_packs)) + + if distribution_strategy == "parameter_server": + return tf.distribute.experimental.ParameterServerStrategy() + + raise ValueError( + "Unrecognized Distribution Strategy: %r" % distribution_strategy) + + +def per_replica_batch_size(batch_size, num_gpus): + """For multi-gpu, batch-size must be a multiple of the number of GPUs. + + + Note that distribution strategy handles this automatically when used with + Keras. For using with Estimator, we need to get per GPU batch. + + Args: + batch_size: Global batch size to be divided among devices. This should be + equal to num_gpus times the single-GPU batch_size for multi-gpu training. + num_gpus: How many GPUs are used with DistributionStrategies. + + Returns: + Batch size per device. + + Raises: + ValueError: if batch_size is not divisible by number of devices + """ + if num_gpus <= 1: + return batch_size + + remainder = batch_size % num_gpus + if remainder: + err = ('When running with multiple GPUs, batch size ' + 'must be a multiple of the number of available GPUs. Found {} ' + 'GPUs with a batch size of {}; try --batch_size={} instead.' + ).format(num_gpus, batch_size, batch_size - remainder) + raise ValueError(err) + return int(batch_size / num_gpus) + + +# The `SyntheticDataset` is a temporary solution for generating synthetic data +# directly on devices. It is only useful for Keras with Distribution +# Strategies. We will have better support in `tf.data` or Distribution Strategy +# later. +class SyntheticDataset(object): + """A dataset that generates synthetic data on each device.""" + + def __init__(self, dataset, split_by=1): + # dataset.take(1) doesn't have GPU kernel. + with tf.device('device:CPU:0'): + tensor = tf.data.experimental.get_single_element(dataset.take(1)) + flat_tensor = tf.nest.flatten(tensor) + variable_data = [] + initializers = [] + for t in flat_tensor: + rebatched_t = tf.split(t, num_or_size_splits=split_by, axis=0)[0] + assert rebatched_t.shape.is_fully_defined(), rebatched_t.shape + v = tf.compat.v1.get_local_variable(self._random_name(), + initializer=rebatched_t) + variable_data.append(v) + initializers.append(v.initializer) + input_data = tf.nest.pack_sequence_as(tensor, variable_data) + self._iterator = SyntheticIterator(input_data, initializers) + + def _random_name(self, size=10, chars=string.ascii_uppercase + string.digits): + return ''.join(random.choice(chars) for _ in range(size)) + + def __iter__(self): + return self._iterator + + def make_one_shot_iterator(self): + return self._iterator + + def make_initializable_iterator(self): + return self._iterator + + +class SyntheticIterator(object): + """A dataset that generates synthetic data on each device.""" + + def __init__(self, input_data, initializers): + self._input_data = input_data + self._initializers = initializers + + def get_next(self): + return self._input_data + + def next(self): + return self.__next__() + + def __next__(self): + try: + return self.get_next() + except tf.errors.OutOfRangeError: + raise StopIteration + + def initialize(self): + if tf.executing_eagerly(): + return tf.no_op() + else: + return self._initializers + + +def _monkey_patch_dataset_method(strategy): + """Monkey-patch `strategy`'s `make_dataset_iterator` method.""" + def make_dataset(self, dataset): + tf.compat.v1.logging.info('Using pure synthetic data.') + with self.scope(): + if self.extended._global_batch_size: # pylint: disable=protected-access + return SyntheticDataset(dataset, self.num_replicas_in_sync) + else: + return SyntheticDataset(dataset) + + def make_iterator(self, dataset): + dist_dataset = make_dataset(self, dataset) + return iter(dist_dataset) + + strategy.orig_make_dataset_iterator = strategy.make_dataset_iterator + strategy.make_dataset_iterator = make_iterator + strategy.orig_distribute_dataset = strategy.experimental_distribute_dataset + strategy.experimental_distribute_dataset = make_dataset + + +def _undo_monkey_patch_dataset_method(strategy): + if hasattr(strategy, 'orig_make_dataset_iterator'): + strategy.make_dataset_iterator = strategy.orig_make_dataset_iterator + if hasattr(strategy, 'orig_distribute_dataset'): + strategy.make_dataset_iterator = strategy.orig_distribute_dataset + + +def set_up_synthetic_data(): + _monkey_patch_dataset_method(tf.distribute.OneDeviceStrategy) + _monkey_patch_dataset_method(tf.distribute.MirroredStrategy) + _monkey_patch_dataset_method( + tf.distribute.experimental.MultiWorkerMirroredStrategy) + + +def undo_set_up_synthetic_data(): + _undo_monkey_patch_dataset_method(tf.distribute.OneDeviceStrategy) + _undo_monkey_patch_dataset_method(tf.distribute.MirroredStrategy) + _undo_monkey_patch_dataset_method( + tf.distribute.experimental.MultiWorkerMirroredStrategy) + + +def configure_cluster(worker_hosts=None, task_index=-1): + """Set multi-worker cluster spec in TF_CONFIG environment variable. + + Args: + worker_hosts: comma-separated list of worker ip:port pairs. + + Returns: + Number of workers in the cluster. + """ + tf_config = json.loads(os.environ.get('TF_CONFIG', '{}')) + if tf_config: + num_workers = (len(tf_config['cluster'].get('chief', [])) + + len(tf_config['cluster'].get('worker', []))) + elif worker_hosts: + workers = worker_hosts.split(',') + num_workers = len(workers) + if num_workers > 1 and task_index < 0: + raise ValueError('Must specify task_index when number of workers > 1') + task_index = 0 if num_workers == 1 else task_index + os.environ['TF_CONFIG'] = json.dumps({ + 'cluster': { + 'worker': workers + }, + 'task': {'type': 'worker', 'index': task_index} + }) + else: + num_workers = 1 + return num_workers + + +def get_strategy_scope(strategy): + if strategy: + strategy_scope = strategy.scope() + else: + strategy_scope = DummyContextManager() + + return strategy_scope + + +class DummyContextManager(object): + + def __enter__(self): + pass + + def __exit__(self, *args): + pass diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/misc/keras_utils.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/misc/keras_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..afa7d00aee0b13238ecc8432f72ea50a9b8489fb --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/misc/keras_utils.py @@ -0,0 +1,273 @@ +# Copyright 2018 The TensorFlow Authors. 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. +# ============================================================================== +"""Helper functions for the Keras implementations of models.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import multiprocessing +import os +import time + +from absl import logging +import tensorflow.compat.v2 as tf +from tensorflow.python import tf2 +from tensorflow.python.profiler import profiler_v2 as profiler + + +class BatchTimestamp(object): + """A structure to store batch time stamp.""" + + def __init__(self, batch_index, timestamp): + self.batch_index = batch_index + self.timestamp = timestamp + + def __repr__(self): + return "'BatchTimestamp'".format( + self.batch_index, self.timestamp) + + +class TimeHistory(tf.keras.callbacks.Callback): + """Callback for Keras models.""" + + def __init__(self, batch_size, log_steps, logdir=None, summary_writer=None, + batch_size_per_node=None): + """Callback for logging performance. + + Args: + batch_size: Total batch size. + log_steps: Interval of steps between logging of batch level stats. + logdir: Optional directory to write TensorBoard summaries. + """ + # TODO(wcromar): remove this parameter and rely on `logs` parameter of + # on_train_batch_end() + self.batch_size = batch_size + self.batch_size_per_node = batch_size_per_node + super(TimeHistory, self).__init__() + self.log_steps = log_steps + self.last_log_step = 0 + self.steps_before_epoch = 0 + self.steps_in_epoch = 0 + self.start_time = None + + if summary_writer is not None: + self.summary_writer = summary_writer + elif logdir: + self.summary_writer = tf.summary.create_file_writer(logdir) + else: + self.summary_writer = None + + # Logs start of step 1 then end of each step based on log_steps interval. + self.timestamp_log = [] + + # Records the time each epoch takes to run from start to finish of epoch. + self.epoch_runtime_log = [] + + @property + def global_steps(self): + """The current 1-indexed global step.""" + return self.steps_before_epoch + self.steps_in_epoch + + @property + def average_steps_per_second(self): + """The average training steps per second across all epochs.""" + return self.global_steps / sum(self.epoch_runtime_log) + + @property + def average_examples_per_second(self): + """The average number of training examples per second across all epochs.""" + return self.average_steps_per_second * self.batch_size + + def on_train_end(self, logs=None): + self.train_finish_time = time.time() + + if self.summary_writer: + self.summary_writer.flush() + + def on_epoch_begin(self, epoch, logs=None): + self.epoch_start = time.time() + + def on_batch_begin(self, batch, logs=None): + if not self.start_time: + self.start_time = time.time() + + # Record the timestamp of the first global step + if not self.timestamp_log: + self.timestamp_log.append(BatchTimestamp(self.global_steps, + self.start_time)) + + def on_batch_end(self, batch, logs=None): + """Records elapse time of the batch and calculates examples per second.""" + self.steps_in_epoch = batch + 1 + steps_since_last_log = self.global_steps - self.last_log_step + if steps_since_last_log >= self.log_steps: + now = time.time() + elapsed_time = now - self.start_time + steps_per_second = steps_since_last_log / elapsed_time + examples_per_second = steps_per_second * self.batch_size + global_examples_per_second = steps_per_second * self.batch_size + if self.batch_size_per_node is not None: + examples_per_second = steps_per_second * self.batch_size_per_node + + self.timestamp_log.append(BatchTimestamp(self.global_steps, now)) + logging.info( + 'TimeHistory: %.2f seconds, %.2f examples/second between steps %d ' + 'and %d', elapsed_time, global_examples_per_second, self.last_log_step, + self.global_steps) + + if self.summary_writer: + with self.summary_writer.as_default(): + tf.summary.scalar('global_step/sec', steps_per_second, + self.global_steps) + tf.summary.scalar('global_examples/sec', global_examples_per_second, + self.global_steps) + if examples_per_second: + # for consistency + tf.summary.scalar('examples/sec', examples_per_second, + self.global_steps) + + self.last_log_step = self.global_steps + self.start_time = None + + def on_epoch_end(self, epoch, logs=None): + epoch_run_time = time.time() - self.epoch_start + self.epoch_runtime_log.append(epoch_run_time) + + self.steps_before_epoch += self.steps_in_epoch + self.steps_in_epoch = 0 + + +def get_profiler_callback(model_dir, profile_steps, enable_tensorboard, + steps_per_epoch): + """Validate profile_steps flag value and return profiler callback.""" + profile_steps_error_message = ( + 'profile_steps must be a comma separated pair of positive integers, ' + 'specifying the first and last steps to be profiled.' + ) + try: + profile_steps = [int(i) for i in profile_steps.split(',')] + except ValueError: + raise ValueError(profile_steps_error_message) + if len(profile_steps) != 2: + raise ValueError(profile_steps_error_message) + start_step, stop_step = profile_steps + if start_step < 0 or start_step > stop_step: + raise ValueError(profile_steps_error_message) + if enable_tensorboard: + logging.warning( + 'Both TensorBoard and profiler callbacks are used. Note that the ' + 'TensorBoard callback profiles the 2nd step (unless otherwise ' + 'specified). Please make sure the steps profiled by the two callbacks ' + 'do not overlap.') + return ProfilerCallback(model_dir, start_step, stop_step, steps_per_epoch) + + +class ProfilerCallback(tf.keras.callbacks.Callback): + """Save profiles in specified step range to log directory.""" + + def __init__(self, log_dir, start_step, stop_step, steps_per_epoch): + super(ProfilerCallback, self).__init__() + self.log_dir = log_dir + self.start_step = start_step + self.stop_step = stop_step + self.start_epoch = start_step // steps_per_epoch + self.stop_epoch = stop_step // steps_per_epoch + self.start_step_in_epoch = start_step % steps_per_epoch + self.stop_step_in_epoch = stop_step % steps_per_epoch + self.should_start = False + self.should_stop = False + + def on_epoch_begin(self, epoch, logs=None): + if epoch == self.start_epoch: + self.should_start = True + if epoch == self.stop_epoch: + self.should_stop = True + + def on_batch_begin(self, batch, logs=None): + if batch == self.start_step_in_epoch and self.should_start: + self.should_start = False + profiler.start(self.log_dir) + logging.info('Profiler started at Step %s', self.start_step) + + def on_batch_end(self, batch, logs=None): + if batch == self.stop_step_in_epoch and self.should_stop: + self.should_stop = False + profiler.stop() + logging.info('Profiler saved profiles for steps between %s and %s to %s', + self.start_step, self.stop_step, self.log_dir) + + +def set_session_config(enable_eager=False, + enable_xla=False): + """Sets the session config.""" + if is_v2_0(): + set_config_v2(enable_xla=enable_xla) + else: + config = get_config_proto_v1(enable_xla=enable_xla) + if enable_eager: + tf.compat.v1.enable_eager_execution(config=config) + else: + sess = tf.compat.v1.Session(config=config) + tf.compat.v1.keras.backend.set_session(sess) + + +def get_config_proto_v1(enable_xla=False): + """Return config proto according to flag settings, or None to use default.""" + config = None + if enable_xla: + config = tf.compat.v1.ConfigProto() + config.graph_options.optimizer_options.global_jit_level = ( + tf.OptimizerOptions.ON_2) + return config + + +def set_config_v2(enable_xla=False): + """Config eager context according to flag values using TF 2.0 API.""" + if enable_xla: + tf.config.optimizer.set_jit(True) + + +def is_v2_0(): + """Returns true if using tf 2.0.""" + return tf2.enabled() + + +def set_gpu_thread_mode_and_count(gpu_thread_mode, + datasets_num_private_threads, + num_gpus, per_gpu_thread_count): + """Set GPU thread mode and count, and adjust dataset threads count.""" + cpu_count = multiprocessing.cpu_count() + logging.info('Logical CPU cores: %s', cpu_count) + + # Allocate private thread pool for each GPU to schedule and launch kernels + per_gpu_thread_count = per_gpu_thread_count or 2 + os.environ['TF_GPU_THREAD_MODE'] = gpu_thread_mode + os.environ['TF_GPU_THREAD_COUNT'] = str(per_gpu_thread_count) + logging.info('TF_GPU_THREAD_COUNT: %s', + os.environ['TF_GPU_THREAD_COUNT']) + logging.info('TF_GPU_THREAD_MODE: %s', + os.environ['TF_GPU_THREAD_MODE']) + + # Limit data preprocessing threadpool to CPU cores minus number of total GPU + # private threads and memory copy threads. + total_gpu_thread_count = per_gpu_thread_count * num_gpus + num_runtime_threads = num_gpus + if not datasets_num_private_threads: + datasets_num_private_threads = min( + cpu_count - total_gpu_thread_count - num_runtime_threads, + num_gpus * 8) + logging.info('Set datasets_num_private_threads to %s', + datasets_num_private_threads) diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/misc/model_helpers.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/misc/model_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..c112bacd4200aa7ec555933be6bedd33ed94df75 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/misc/model_helpers.py @@ -0,0 +1,93 @@ +# Copyright 2018 The TensorFlow Authors. 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. +# ============================================================================== +"""Miscellaneous functions that can be called by models.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numbers + +import tensorflow as tf +from tensorflow.python.util import nest + + +def past_stop_threshold(stop_threshold, eval_metric): + """Return a boolean representing whether a model should be stopped. + + Args: + stop_threshold: float, the threshold above which a model should stop + training. + eval_metric: float, the current value of the relevant metric to check. + + Returns: + True if training should stop, False otherwise. + + Raises: + ValueError: if either stop_threshold or eval_metric is not a number + """ + if stop_threshold is None: + return False + + if not isinstance(stop_threshold, numbers.Number): + raise ValueError("Threshold for checking stop conditions must be a number.") + if not isinstance(eval_metric, numbers.Number): + raise ValueError("Eval metric being checked against stop conditions " + "must be a number.") + + if eval_metric >= stop_threshold: + tf.compat.v1.logging.info( + "Stop threshold of {} was passed with metric value {}.".format( + stop_threshold, eval_metric)) + return True + + return False + + +def generate_synthetic_data( + input_shape, input_value=0, input_dtype=None, label_shape=None, + label_value=0, label_dtype=None): + """Create a repeating dataset with constant values. + + Args: + input_shape: a tf.TensorShape object or nested tf.TensorShapes. The shape of + the input data. + input_value: Value of each input element. + input_dtype: Input dtype. If None, will be inferred by the input value. + label_shape: a tf.TensorShape object or nested tf.TensorShapes. The shape of + the label data. + label_value: Value of each input element. + label_dtype: Input dtype. If None, will be inferred by the target value. + + Returns: + Dataset of tensors or tuples of tensors (if label_shape is set). + """ + # TODO(kathywu): Replace with SyntheticDataset once it is in contrib. + element = input_element = nest.map_structure( + lambda s: tf.constant(input_value, input_dtype, s), input_shape) + + if label_shape: + label_element = nest.map_structure( + lambda s: tf.constant(label_value, label_dtype, s), label_shape) + element = (input_element, label_element) + + return tf.data.Dataset.from_tensors(element).repeat() + + +def apply_clean(flags_obj): + if flags_obj.clean and tf.io.gfile.exists(flags_obj.model_dir): + tf.compat.v1.logging.info("--clean flag set. Removing existing model dir:" + " {}".format(flags_obj.model_dir)) + tf.io.gfile.rmtree(flags_obj.model_dir) diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/misc/tpu_lib.py b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/misc/tpu_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..4d4cddb1c6b015091ed2da57df49277e3008c252 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/utils/misc/tpu_lib.py @@ -0,0 +1,34 @@ +# Copyright 2019 The TensorFlow Authors. 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. +# ============================================================================== +"""Initializes TPU system for TF 2.0.""" + +import tensorflow as tf + + +def tpu_initialize(tpu_address): + """Initializes TPU for TF 2.0 training. + + Args: + tpu_address: string, bns address of master TPU worker. + + Returns: + A TPUClusterResolver. + """ + cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver( + tpu=tpu_address) + if tpu_address not in ('', 'local'): + tf.config.experimental_connect_to_cluster(cluster_resolver) + tf.tpu.experimental.initialize_tpu_system(cluster_resolver) + return cluster_resolver diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/scripts/launch_keras_resnet_hvd.sh b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/scripts/launch_keras_resnet_hvd.sh new file mode 100644 index 0000000000000000000000000000000000000000..bddef499d2ef46042b9898846def31c8b814eab7 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/scripts/launch_keras_resnet_hvd.sh @@ -0,0 +1,618 @@ +#!/bin/bash + +DEBUG=${DEBUG:-0} +if [[ $DEBUG -eq 1 ]]; then + set -x + env +fi + +# Basic paths +SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) +export BASE_PATH="$( cd "$(dirname "$(readlink -e ${SCRIPT_DIR}/TensorFlow)" )" && pwd)" + +PYTHONPATH=${BASE_PATH}:$PYTHONPATH +IMAGENET_DIR=/root/datasets/imagenet/tf_records +exit_code=0 + +# Determine OpenMPI prefix from location of mpirun in the system +OMPI_PREFIX=$(which mpirun) +if [[ ! -z $OMPI_PREFIX ]]; then + OMPI_PREFIX=$(dirname $(dirname ${OMPI_PREFIX}) ) +fi + +# Fixed variables needed by this script +export NUM_WORKERS_PER_HLS=${NUM_WORKERS_PER_HLS:-4} +export HLS_TYPE=${HLS_TYPE:-HLS2} + +function help() +{ + echo "Usage:" + echo "$0 [ -key1 value1 -key2 value2 .... -keyn valuen ]" + echo "-b | --batch-size Batch size" + echo "-c | --config Configuration file path (defaults to ./defaults.cfg)" + echo "-p | --cpu-pin [ none | cpu | numa ]" + echo "-a | --data-dir Imagenet data directory" + echo "-m | --model-dir Model dir, defaults to /tmp/resnet_50" + echo "-dc | --dataset_cache Enable (true) or disable (false) dataset caching" + echo "-noEval | --disable_eval Enable (0) or disable (1) evaluation" + echo "-bf16 | --enable_bf16" + echo "-mlperf | --enable_mlperf" + echo "-e | --epochs Number of epochs" + echo "-ebe | --epochs_between_eval Number of training epochs between eval" + echo "-eof | --epoch_eval_offset" + echo "-hf | --hostfile Host file path, 'localhost' is used if no file is provided" + echo "-lbs | --label_smoothing" + echo "-l | --lars-opt Enable LARS optimizer" + echo "-lde | --lars_decay_epochs" + echo "-mm | --momentum" + echo "-md | --modeling Enable (1) or disable (0) TF dumpos for SPARTA modeling" + echo "-w | --number-worker Number of Gaudis" + echo "-rs | --resnet-size Resnet size" + echo "-slr | --start_learning_rate" + echo "-sth | --stop_thold Target accuracy" + echo "-s | --steps Display logs for evey number of steps" + echo "-sl | --steps-per-loop Number of steps per loop in Keras implementation" + echo "-sd | --synthetic_data Enable (1) or disable (0) synthetic dataset" + echo "-tev | --train_eval" + echo "-ts | --train_steps Train steps, will be overwritten if epochs > 0" + echo "-u | --use_horovod Enable (1) or disable (0) horovod use" + echo "-we | --warmup_epochs" + echo "-wd | --weight_decay" + echo "-nas | --num_accumulation_steps" + echo "-crc | --clean_recipe_cache Clean TF recipe cache Enable (1) disable (0), default: 1" + echo "-tcp | --mpi_tcp_include" + echo "-log | --log_dir" + echo "-ps | --pod_size" + echo "-ntf | --num_train_files Number of training tf records" + echo "-nef | --num_eval_files Number of evaluation tf records" + echo "-sfg | --signaling_from_graph Enable (1) or disable (0) signaling from graph, default is 1" +} + +function getmulti_hls_ips() +{ + if [[ $USE_HOROVOD -ne 1 ]]; then + return + fi + + multi_hcl_ip="MULTI_HLS_IPS=" + hostsFile=$1 + firstHost=1 + hostCount=0 + + # iterate over non-empty and non-commented lines + for h in $(cat $hostsFile | sed '/^$/d' | grep -v '^#'); do + if [[ $firstHost -eq 1 ]]; then + firstHost=0 + else + multi_hcl_ip+="," + fi + multi_hcl_ip+=$h + hostCount=$((hostCount + 1)) + done + + echo "[getmulti_hls_ips] Host Count : $hostCount" + echo "[getmulti_hls_ips] Exporting : $multi_hcl_ip" + export $multi_hcl_ip +} + +function generate_mpi_hostfile() +{ + if [[ $USE_HOROVOD -ne 1 ]]; then + return + fi + + echo "Generating MPI hostfile..." + local num_nodes=${2:-8} + local file_name="hostfile" + export MPI_HOSTFILE_PATH=$1/${file_name} + + rm -rf ${MPI_HOSTFILE_PATH} + echo "PATH: ${MPI_HOSTFILE_PATH}" + touch ${MPI_HOSTFILE_PATH} + + IFS=',' read -ra IPS <<< "$MULTI_HLS_IPS" + for i in "${IPS[@]}"; do + echo "$i slots=${num_nodes}" >> ${MPI_HOSTFILE_PATH} + done + + echo "Config: " + cat ${MPI_HOSTFILE_PATH} +} + +function run_per_ip() +{ + if [[ $USE_HOROVOD -ne 1 ]]; then + _cmd="$@" + $_cmd + return 0 + fi + + if [ -n "$OMPI_COMM_WORLD_SIZE" ]; then + print_error "Function run_per_ip is not meant to be ran from within an OpenMPI context. It is intended to invoke mpirun by itelf." + exit 1 + fi + + _cmd="$@" + + if [[ -z ${MULTI_HLS_IPS} ]]; then + echo "[launch_keras_resnet_hvd] MULTI_HLS_IPS undefined - maybe a missing /root/shared/hosts file?" + exit -1 + else + if [ -n "$MPI_TCP_INCLUDE" ]; then + _option_btl_tcp_if_include="--mca btl_tcp_if_include ${MPI_TCP_INCLUDE}" + else + _option_btl_tcp_if_include="" + fi + + mpirun --allow-run-as-root \ + --mca plm_rsh_args -p${SSH_PORT} \ + ${_option_btl_tcp_if_include} \ + --tag-output \ + --merge-stderr-to-stdout \ + --prefix ${OMPI_PREFIX} \ + -H ${MULTI_HLS_IPS} \ + bash -c "`declare`; `declare -x`; ($_cmd 2>&1)" 2>/dev/null + fi +} + +# Parse command line options +unset __bsize +unset __config +unset __data_dir +unset __jpeg_data_dir +unset __dataset_cache +unset __disable_eval +unset __enable_bf16_conversion +unset __enable_lars +unset __enable_mlperf +unset __epochs +unset __epochs_between_eval +unset __eval_offset_epochs +unset __hostfile +unset __label_smoothing +unset __lars_decay_epochs +unset __momentum +unset __modeling +unset __number_Worker +unset __resnetSize +unset __run_number +unset __start_learning_rate +unset __steps +unset __steps_per_loop +unset __stop_thold +unset __train_eval +unset __train_steps +unset __use_horovod +unset __synthetic_data +unset __warmup_epochs +unset __weight_decay +unset __num_accumulation_steps +unset __workload_to_cpu_pin_type +unset __dataset_cache +unset __clean_recipe_cache +unset __mpi_tcp_include +unset __log_dir +unset __model_dir +unset __pod_size +unset __num_train_files +unset __num_eval_files +unset __ssh_port +unset __signaling_from_graph + +while [ -n "$1" ]; do + case $1 in + -rs | --resnet-size ) + shift + __resnetSize=$1 + ;; + -c | --config ) + shift + __config=$1 + ;; + -a | --data-dir ) + shift + __data_dir=$1 + ;; + -ja | --jpeg-data-dir ) + shift + __jpeg_data_dir=$1 + ;; + -m | --model-dir ) + shift + __model_dir=$1 + ;; + -b | --batch-size ) + shift + __bsize=$1 + ;; + -s | --steps ) + shift + __steps=$1 + ;; + -sl | --steps-per-loop ) + shift + __steps_per_loop=$1 + ;; + -e | --epochs ) + shift + __epochs=$1 + ;; + -w | --number-worker ) + shift + __number_Worker=$1 + ;; + -hf | --hostfile) + shift + __hostfile=$1 + ;; + -l | --lars-opt) + shift + __enable_lars=$1 + ;; + -dc | --dataset_cache) + shift + __dataset_cache=$1 + ;; + -ebe | --epochs_between_eval) + shift + __epochs_between_eval=$1 + ;; + -ts | --train_steps) + shift + __train_steps=$1 + ;; + -we | --warmup_epochs) + shift + __warmup_epochs=$1 + ;; + -wd | --weight_decay) + shift + __weight_decay=$1 + ;; + -nas | --num_accumulation_steps) + shift + __num_accumulation_steps=$1 + ;; + -lbs | --label_smoothing) + shift + __label_smoothing=$1 + ;; + -slr | --start_learning_rate) + shift + __start_learning_rate=$1 + ;; + -sd | --synthetic_data) + shift + __synthetic_data=$1 + ;; + -mlperf | --enable_mlperf) + shift + __enable_mlperf=$1 + ;; + -noEval | --disable_eval) + shift + __disable_eval=$1 + ;; + -tev | --train_eval) + shift + __train_eval=$1 + ;; + -bf16 | --enable_bf16) + shift + __enable_bf16_conversion=$1 + ;; + -eof | --epoch_eval_offset) + shift + __eval_offset_epochs=$1 + ;; + -sth | --stop_thold) + shift + __stop_thold=$1 + ;; + -mm | --momentum) + shift + __momentum=$1 + ;; + -md | --modeling) + shift + __modeling=$1 + ;; + -rn | --run-number ) + shift + __run_number=$1 + ;; + -p | --cpu-pin) + shift + __workload_to_cpu_pin_type=$1 + case ${__workload_to_cpu_pin_type} in + numa | cpu | none ) + ;; + *) + echo "--cpu-pin must be one of the following numa | cpu | none " + exit 1 + esac + ;; + -u | --use_horovod) + shift + __use_horovod=$1 + ;; + -dc | --dataset_cache) + shift + __dataset_cache=$1 + ;; + -lde | --lars_decay_epochs) + shift + __lars_decay_epochs=$1 + ;; + -crc | --clean_recipe_cache) + shift + __clean_recipe_cache=$1 + ;; + -tcp | --mpi_tcp_include) + shift + __mpi_tcp_include=$1 + ;; + -log | --log_dir) + shift + __log_dir=$1 + ;; + -ps | --pod_size) + shift + __pod_size=$1 + ;; + -ntf | --num_train_files) + shift + __num_train_files=$1 + ;; + -nef | --num_eval_files) + shift + __num_eval_files=$1 + ;; + -port | --ssh_port) + shift + __ssh_port=$1 + ;; + -sfg | --signaling_from_graph) + shift + __signaling_from_graph=$1 + ;; + -h | --help) + help + exit 1 + ;; + * ) + echo "The parameter $1 is not allowed" + help + ;; + esac + shift +done + +# Set default values for environmental variable +export CFG_FILE=${__config:-"${BASE_PATH}/defaults.cfg"} +export HOST_FILE=${__hostfile:-"${OMPI_MCA_orte_default_hostfile}"} +export SSH_PORT=${__ssh_port:-"3022"} + +if [[ -f ${CFG_FILE} ]]; then + source ${CFG_FILE} +else + echo "Could not find ${CFG_FILE}" + exit 1 +fi + +# Set default directory name +WORK_DIR=/tmp/resnet50 + +# set default LOG_DIR +export testdate=`date +%Y-%m-%d` +export testtime=`date +%H%M%S` +export LOG_DIR=/root/scratch/resnet/resnet_gaudi${NUM_WORKERS}_${testdate}_${testtime} + +# Override defaults with command line options if needed +export RESNET_SIZE=${__resnetSize:-"$RESNET_SIZE"} +export IMAGENET_DIR=${__data_dir:-"$IMAGENET_DIR"} +export JPEG_IMAGENET_DIR=${__jpeg_data_dir:-"$JPEG_IMAGENET_DIR"} +export BATCH_SIZE=${__bsize:-"$BATCH_SIZE"} +export TRAIN_EPOCHS=${__epochs:-"$TRAIN_EPOCHS"} +export TRAIN_STEPS=${__train_steps:-"$TRAIN_STEPS"} +export DISPLAY_STEPS=${__steps:-"$DISPLAY_STEPS"} +export STEPS_PER_LOOP=${__steps_per_loop:-"$STEPS_PER_LOOP"} +export NUM_WORKERS=${__number_Worker:-"$NUM_WORKERS"} +export USE_LARS_OPTIMIZER=${__enable_lars:-"$USE_LARS_OPTIMIZER"} +export CPU_BIND_TYPE=${__workload_to_cpu_pin_type:-"$CPU_BIND_TYPE"} +export EPOCHS_BETWEEN_EVALS=${__epochs_between_eval:-"$EPOCHS_BETWEEN_EVALS"} +export WEIGHT_DECAY=${__weight_decay:-"$WEIGHT_DECAY"} +export NUM_ACCUMULATION_STEPS=${__num_accumulation_steps:-"$NUM_ACCUMULATION_STEPS"} +export LABEL_SMOOTH=${__label_smoothing:-"$LABEL_SMOOTH"} +export BASE_LEARNING_RATE=${__start_learning_rate:-"$BASE_LEARNING_RATE"} +export WARMUP_EPOCHS=${__warmup_epochs:-"$WARMUP_EPOCHS"} +export USE_MLPERF=${__enable_mlperf:-"$USE_MLPERF"} +export NO_EVAL=${__disable_eval:-"$NO_EVAL"} +export STOP_THRESHOLD=${__stop_thold:-"$STOP_THRESHOLD"} +export LR_MOMENTUM=${__momentum:-"$LR_MOMENTUM"} +export EVAL_OFFSET_EPOCHS=${__eval_offset_epochs:-"$EVAL_OFFSET_EPOCHS"} +export TF_BF16_CONVERSION=${__enable_bf16_conversion:-"$TF_BF16_CONVERSION"} +export USE_HOROVOD=${__use_horovod:-"$USE_HOROVOD"} +export DATASET_CACHE=${__dataset_cache:-"$DATASET_CACHE"} +export LARS_DECAY_EPOCHS=${__lars_decay_epochs:-"$LARS_DECAY_EPOCHS"} +export SYNTHETIC_DATA=${__synthetic_data:-"$SYNTHETIC_DATA"} +if [ -z ${__train_eval} ]; then + export TRAIN_AND_EVAL=${__train_eval:-"$TRAIN_AND_EVAL"} +fi +export TRAIN_STEPS=${TRAIN_STEPS:--1} +export MODELING=${__modeling:-"$MODELING"} +export CLEAN_RECIPE_CACHE=${__clean_recipe_cache:-1} +export MPI_TCP_INCLUDE=${__mpi_tcp_include:-$MPI_TCP_INCLUDE} +export LOG_DIR=${__log_dir:-"$LOG_DIR"} +export WORK_DIR=${__model_dir:-"$WORK_DIR"} +export NUM_TRAIN_FILES=${__num_train_files:-"$NUM_TRAIN_FILES"} +export NUM_EVAL_FILES=${__num_eval_files:-"$NUM_EVAL_FILES"} +# Workaound on SW-75839 +export TF_ENABLE_DYNAMIC_SHAPES=${TF_ENABLE_DYNAMIC_SHAPES:-false} +export SIGNALING_FROM_GRAPH=${__signaling_from_graph:-1} + +echo "[launch_keras_resnet_hvd] General Settings:" +echo "[launch_keras_resnet_hvd] CFG_FILE" $CFG_FILE +echo "[launch_keras_resnet_hvd] HOST_FILE" $HOST_FILE +echo "[launch_keras_resnet_hvd] NUM_WORKERS" $NUM_WORKERS +echo "[launch_keras_resnet_hvd] RESNET_SIZE" $RESNET_SIZE +echo "[launch_keras_resnet_hvd] IMAGENET_DIR" $IMAGENET_DIR +echo "[launch_keras_resnet_hvd] JPEG_IMAGENET_DIR" $JPEG_IMAGENET_DIR +echo "[launch_keras_resnet_hvd] BATCH_SIZE" $BATCH_SIZE +echo "[launch_keras_resnet_hvd] TRAIN_EPOCHS" $TRAIN_EPOCHS +echo "[launch_keras_resnet_hvd] TRAIN_STEPS" $TRAIN_STEPS +echo "[launch_keras_resnet_hvd] DISPLAY_STEPS" $DISPLAY_STEPS +echo "[launch_keras_resnet_hvd] USE_LARS_OPTIMIZER" $USE_LARS_OPTIMIZER +echo "[launch_keras_resnet_hvd] CPU_BIND_TYPE" $CPU_BIND_TYPE +echo "[launch_keras_resnet_hvd] EPOCHS_BETWEEN_EVALS" $EPOCHS_BETWEEN_EVALS +echo "[launch_keras_resnet_hvd] TRAIN_AND_EVAL" $TRAIN_AND_EVAL +echo "[launch_keras_resnet_hvd] TF_BF16_CONVERSION" $TF_BF16_CONVERSION +echo "[launch_keras_resnet_hvd] USE_HOROVOD" $USE_HOROVOD +echo "[launch_keras_resnet_hvd] DATASET_CACHE" $DATASET_CACHE +echo "[launch_keras_resnet_hvd] MODELING" $MODELING +echo "[launch_keras_resnet_hvd] MPI_TCP_INCLUDE" $MPI_TCP_INCLUDE +echo "[launch_keras_resnet_hvd] LOG_DIR" $LOG_DIR +echo "[launch_keras_resnet_hvd] NUM_TRAIN_FILES" $NUM_TRAIN_FILES +echo "[launch_keras_resnet_hvd] NUM_EVAL_FILES" $NUM_EVAL_FILES +echo +echo "[launch_keras_resnet_hvd] Learning Setting:" +echo "[launch_keras_resnet_hvd] WEIGHT_DECAY" $WEIGHT_DECAY +echo "[launch_keras_resnet_hvd] NUM_ACCUMULATION_STEPS" $NUM_ACCUMULATION_STEPS +echo "[launch_keras_resnet_hvd] LABEL_SMOOTH" $LABEL_SMOOTH +echo "[launch_keras_resnet_hvd] BASE_LEARNING_RATE" $BASE_LEARNING_RATE +echo "[launch_keras_resnet_hvd] WARMUP_EPOCHS" $WARMUP_EPOCHS +echo "[launch_keras_resnet_hvd] USE_MLPERF" $USE_MLPERF +echo "[launch_keras_resnet_hvd] NO_EVAL" $NO_EVAL +echo "[launch_keras_resnet_hvd] STOP_THRESHOLD" $STOP_THRESHOLD +echo "[launch_keras_resnet_hvd] LR_MOMENTUM" $LR_MOMENTUM +echo "[launch_keras_resnet_hvd] EVAL_OFFSET_EPOCHS" $EVAL_OFFSET_EPOCHS +echo "[launch_keras_resnet_hvd] LARS_DECAY_EPOCHS" $LARS_DECAY_EPOCHS +echo "[launch_keras_resnet_hvd] SYNTHETIC_DATA" $SYNTHETIC_DATA +echo "[launch_keras_resnet_hvd] WORK_DIR" $WORK_DIR +echo "[launch_keras_resnet_hvd] TF_ENABLE_DYNAMIC_SHAPES" $TF_ENABLE_DYNAMIC_SHAPES +echo "[launch_keras_resnet_hvd] SIGNALING_FROM_GRAPH" $SIGNALING_FROM_GRAPH + +# This check always needs to go after all environment variable proccessing is complete. +if [ ! -d ${IMAGENET_DIR} ] && [ ! -d ${JPEG_IMAGENET_DIR} ]; then + echo "[launch_keras_resnet_hvd] ImageNet image database not found on ${IMAGENET_DIR}" + exit -1 +fi + +rm -rf $LOG_DIR +mkdir -p $WORK_DIR +mkdir -p $LOG_DIR + +export MULTI_HLS_IPS=localhost +if [[ -f ${HOST_FILE} ]]; then + getmulti_hls_ips ${HOST_FILE} +fi + +# Setup the cahe directory and create ramdisk +export TF_RECIPE_CACHE_PATH=${WORK_DIR}/graph_dump_recipes +if [[ $CLEAN_RECIPE_CACHE -eq 1 ]]; then + run_per_ip rm -rf ${TF_RECIPE_CACHE_PATH} +fi +run_per_ip rm -rf ${WORK_DIR}/resnet_synth_data +run_per_ip mkdir -p ${TF_RECIPE_CACHE_PATH} + +run_per_ip 'mkdir -p ${BASE_PATH}/log' + +printf "[launch_keras_resnet_hvd] Cleaning temp files...\n\n" +run_per_ip rm -rf /tmp/checkpoint /tmp/eval /tmp/events.out.tfevents.* /tmp/graph.pbtxt /tmp/model.ckpt-* +run_per_ip rm -rf /tmp/rank_*/checkpoint /tmp/rank_*/eval /tmp/rank_*/events.out.tfevents.* /tmp/rank_*/graph.pbtxt /tmp/rank_*/model.ckpt-* + +if [[ $USE_HOROVOD -eq 1 ]]; then + + if [[ -z ${MULTI_HLS_IPS} ]]; then + echo "[launch_keras_resnet_hvd] MULTI_HLS_IPS undefined - maybe a missing /root/shared/hosts file?" + exit -1 + fi + + generate_mpi_hostfile ${WORK_DIR} ${NUM_WORKERS_PER_HLS} + + # Substituted this by the calculation below + #calc_optimal_cpu_resources_for_mpi veces leri + MPI_MAP_BY=socket + MPI_MAP_BY_PE=`lscpu | grep "^CPU(s):"| awk -v NUM=${NUM_WORKERS_PER_HLS} '{print int($2/NUM/2)}'` + if [[ "$CPU_BIND_TYPE" == "numa" || "$CPU_BIND_TYPE" == "none" ]]; then + MPIRUN_ARGS_MAP_BY_PE="-bind-to none" + else + MPIRUN_ARGS_MAP_BY_PE="--bind-to core --map-by $MPI_MAP_BY:PE=$MPI_MAP_BY_PE" + fi + + if [ -n "$MPI_TCP_INCLUDE" ]; then + _option_btl_tcp_if_include="--mca btl_tcp_if_include ${MPI_TCP_INCLUDE}" + else + _option_btl_tcp_if_include="" + fi + + TRAINING_COMMAND="mpirun --allow-run-as-root \ + -np $NUM_WORKERS --hostfile ${MPI_HOSTFILE_PATH} \ + --prefix ${OMPI_PREFIX} \ + --mca plm_rsh_args -p${SSH_PORT} \ + ${_option_btl_tcp_if_include} \ + -x BASE_PATH=${BASE_PATH} \ + -x PYTHONPATH=${PYTHONPATH} \ + -x DATASET_CACHE=${DATASET_CACHE} \ + -x DEBUG=${DEBUG} \ + -x RESNET_SIZE=${RESNET_SIZE} \ + -x IMAGENET_DIR=${IMAGENET_DIR} \ + -x JPEG_IMAGENET_DIR=${JPEG_IMAGENET_DIR} \ + -x TF_BF16_CONVERSION=${TF_BF16_CONVERSION} \ + -x TF_RECIPE_CACHE_PATH=${TF_RECIPE_CACHE_PATH} \ + -x LD_PRELOAD=${LD_PRELOAD} \ + -x TF_MODULES_RELEASE_BUILD=${TF_MODULES_RELEASE_BUILD} \ + -x HABANA_LOGS=${HABANA_LOGS} \ + -x CPU_BIND_TYPE=${CPU_BIND_TYPE} \ + -x WORK_DIR=${WORK_DIR} \ + -x BATCH_SIZE=${BATCH_SIZE} \ + -x TRAIN_EPOCHS=${TRAIN_EPOCHS} \ + -x TRAIN_STEPS=${TRAIN_STEPS} \ + -x DISPLAY_STEPS=${DISPLAY_STEPS} \ + -x STEPS_PER_LOOP=${STEPS_PER_LOOP} \ + -x NUM_WORKERS=${NUM_WORKERS} \ + -x EPOCHS_BETWEEN_EVALS=${EPOCHS_BETWEEN_EVALS} \ + -x EVAL_OFFSET_EPOCHS=${EVAL_OFFSET_EPOCHS} \ + -x WARMUP_EPOCHS=${WARMUP_EPOCHS} \ + -x LABEL_SMOOTH=${LABEL_SMOOTH} \ + -x WEIGHT_DECAY=${WEIGHT_DECAY} \ + -x NUM_ACCUMULATION_STEPS=${NUM_ACCUMULATION_STEPS} + -x LR_MOMENTUM=${LR_MOMENTUM} \ + -x USE_LARS_OPTIMIZER=${USE_LARS_OPTIMIZER} \ + -x SYNTHETIC_DATA=${SYNTHETIC_DATA} \ + -x BASE_LEARNING_RATE=${BASE_LEARNING_RATE} \ + -x USE_MLPERF=${USE_MLPERF} \ + -x ENABLE_BARRIERS=0 \ + -x SCALE_OUT_PORTS=1 \ + -x STOP_THRESHOLD=${STOP_THRESHOLD} \ + -x NO_EVAL=${NO_EVAL} \ + -x USE_HOROVOD=${USE_HOROVOD} \ + -x TRAIN_STEPS=${TRAIN_STEPS} \ + -x LARS_DECAY_EPOCHS=${LARS_DECAY_EPOCHS} \ + -x LOG_DIR=${LOG_DIR} \ + -x NUM_TRAIN_FILES=${NUM_TRAIN_FILES} \ + -x NUM_EVAL_FILES=${NUM_EVAL_FILES} \ + -x TF_ENABLE_DYNAMIC_SHAPES=${TF_ENABLE_DYNAMIC_SHAPES} \ + ${MPIRUN_ARGS_MAP_BY_PE} \ + -x MODELING=${MODELING} \ + -x HOROVOD_FUSION_THRESHOLD \ + -x SIGNALING_FROM_GRAPH \ + --merge-stderr-to-stdout --output-filename ${LOG_DIR} \ + ${SCRIPT_DIR}/run.sh" + +else + TRAINING_COMMAND="${SCRIPT_DIR}/run.sh" +fi + +echo "TRAINING COMMAND = ${TRAINING_COMMAND}" +printf "[launch_keras_resnet_hvd] Starting training...\n\n" +$TRAINING_COMMAND + +run_per_ip rm -rf ${WORK_DIR}/resnet_synth_data + +rm -rf ${BASE_PATH}/log +cp /root/build_log.csv ${LOG_DIR}/ +cp ${MPI_HOSTFILE_PATH} ${LOG_DIR}/ +cp -r ${LOG_DIR} ${BASE_PATH}/log +chmod -R 777 ${LOG_DIR} +exit $exit_code diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/scripts/run.sh b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/scripts/run.sh new file mode 100644 index 0000000000000000000000000000000000000000..65f07b0bd320430f513ed8078d0c1b9ee31d8f80 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/scripts/run.sh @@ -0,0 +1,168 @@ +#!/bin/bash + +if [[ $DEBUG -eq 1 ]]; then + set -x + env + #LOG_LEVEL:0 - TRACE, 1 - DEBUG, 2 - INFO, 3 - WARNING, 4 - ERROR, 5 - CRITICAL, 6 - OFF + export LOG_LEVEL_ALL_HCL=2 +else + export LOG_LEVEL_ALL_HCL=6 +fi + +if [ -z $BASE_PATH ]; then + BASE_PATH="$( cd "$(dirname "$(readlink -f ./defaults.cfg)" )" && pwd)" + PYTHONPATH=${BASE_PATH}:$PYTHONPATH +fi + +TRAIN_SCRIPT=${BASE_PATH}/TensorFlow/computer_vision/Resnets/resnet_keras/resnet_ctl_imagenet_main.py +PT_VERSION=`python3 -c 'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}")'` +TF_VERSION=`python3 -c "import tensorflow as tf; print(tf.__version__.replace('.', '_'))"` +PATCH_PATH=/usr/local/lib/python${PT_VERSION}/dist-packages/habana_frameworks/tensorflow/tf${TF_VERSION}/lib/habanalabs +# This is required for HW profiling but does not hurt so we add it always +export PYTHONPATH=${PATCH_PATH}:${PYTHONPATH} + +# Fixed varaibles, not inherited from launcher +export TF_ALLOW_CONTROL_EDGES_IN_HABANA_OPS=1 +export EXPERIMENTAL_PRELOADING=1 +export ENABLE_TENSORBOARD=false +export REPORT_ACCURACY_METRICS=true +export DIST_EVAL=true +export ENABLE_DEVICE_WARMUP=true +export TF_DISABLE_MKL=1 +export SYNTHETIC_DATA=${SYNTHETIC_DATA} + +if [[ $MODELING -eq 1 ]]; then + ENABLE_CHECKPOINT=true +else + ENABLE_CHECKPOINT=false +fi +if [[ $TF_BF16_CONVERSION -eq 1 ]]; then + DATA_TYPE="bf16" +else + DATA_TYPE="fp32" +fi +if [[ ${NO_EVAL} -eq 1 ]]; then + SKIP_EVAL=true +else + SKIP_EVAL=false +fi +if [[ ${USE_LARS_OPTIMIZER} -eq 1 ]]; then + OPTIMIZER="LARS" +else + OPTIMIZER="SGD" +fi +if [[ ${USE_HOROVOD} -eq 1 ]]; then + DIST_EVAL=true + USE_HOROVOD='--use_horovod' +else + DIST_EVAL=false + USE_HOROVOD='' +fi +if [[ ${SYNTHETIC_DATA} -eq 1 ]]; then + SYNTHETIC_DATA=true +fi +if [[ -n ${NUM_ACCUMULATION_STEPS} ]]; then + NUM_ACCUMULATION_STEPS="--num_acc_steps=${NUM_ACCUMULATION_STEPS}" +else + NUM_ACCUMULATION_STEPS="" +fi + +if [[ -n ${JPEG_IMAGENET_DIR} ]]; then + JPEG_IMAGENET_DIR="--jpeg_data_dir=${JPEG_IMAGENET_DIR}" +fi + +if [[ $SIGNALING_FROM_GRAPH -eq 1 ]]; then + export HOROVOD_FUSION_THRESHOLD=0 + export TF_USE_SIGNALING_FROM_ENCAP_OP=1 +else + export TF_USE_SIGNALING_FROM_ENCAP_OP=0 +fi + +# clear cache +PROC_FS=${PROC_FS:-"/proc"} +sync && echo 3 > $PROC_FS/sys/vm/drop_caches + +TRAIN_COMMAND="python3 ${TRAIN_SCRIPT} + --model_dir=${WORK_DIR} + --data_dir=${IMAGENET_DIR} + ${JPEG_IMAGENET_DIR} + --batch_size=${BATCH_SIZE} + --distribution_strategy=off + --num_gpus=0 + --data_format=channels_last + --train_epochs=${TRAIN_EPOCHS} + --train_steps=${TRAIN_STEPS} + --experimental_preloading=${EXPERIMENTAL_PRELOADING} + --log_steps=${DISPLAY_STEPS} + --steps_per_loop=${STEPS_PER_LOOP} + --enable_checkpoint_and_export=${ENABLE_CHECKPOINT} + --enable_tensorboard=${ENABLE_TENSORBOARD} + --epochs_between_evals=${EPOCHS_BETWEEN_EVALS} + --base_learning_rate=${BASE_LEARNING_RATE} + --warmup_epochs=${WARMUP_EPOCHS} + --optimizer=${OPTIMIZER} + --lr_schedule=polynomial + --label_smoothing=${LABEL_SMOOTH} + --weight_decay=${WEIGHT_DECAY} + $NUM_ACCUMULATION_STEPS + --single_l2_loss_op + ${USE_HOROVOD} + --modeling=${MODELING} + --data_loader_image_type=${DATA_TYPE} + --dtype=${DATA_TYPE} + --eval_offset_epochs=${EVAL_OFFSET_EPOCHS} + --report_accuracy_metrics=${REPORT_ACCURACY_METRICS} + --dist_eval=${DIST_EVAL} + --target_accuracy=${STOP_THRESHOLD} + --enable_device_warmup=${ENABLE_DEVICE_WARMUP} + --lars_decay_epochs=${LARS_DECAY_EPOCHS} + --momentum=${LR_MOMENTUM} + --skip_eval=${SKIP_EVAL} + --use_synthetic_data=${SYNTHETIC_DATA} + --dataset_cache=${DATASET_CACHE} + --num_train_files=${NUM_TRAIN_FILES} + --num_eval_files=${NUM_EVAL_FILES} +" +echo ${TRAIN_COMMAND} + +echo "[run] General Settings:" +echo "[run] RESNET_SIZE" $RESNET_SIZE +echo "[run] IMAGENET_DIR" $IMAGENET_DIR +echo "[run] BATCH_SIZE" $BATCH_SIZE +echo "[run] NUM_WORKERS" $NUM_WORKERS +echo "[run] TRAIN_EPOCHS" $TRAIN_EPOCHS +echo "[run] TRAIN_STEPS" $TRAIN_STEPS +echo "[run] DISPLAY_STEPS" $DISPLAY_STEPS +echo "[run] USE_LARS_OPTIMIZER" $USE_LARS_OPTIMIZER +echo "[run] CPU_BIND_TYPE" $CPU_BIND_TYPE +echo "[run] EPOCHS_BETWEEN_EVALS" $EPOCHS_BETWEEN_EVALS +echo "[run] TRAIN_AND_EVAL" $TRAIN_AND_EVAL +echo "[run] TF_BF16_CONVERSION" $TF_BF16_CONVERSION +echo "[run] DATASET_CACHE" $DATASET_CACHE +echo "[run] USE_HOROVOD" $USE_HOROVOD +echo +echo "[run] Learning Setting:" +echo "[run] WEIGHT_DECAY" $WEIGHT_DECAY +echo "[run] NUM_ACCUMULATION_STEPS" $NUM_ACCUMULATION_STEPS +echo "[run] LABEL_SMOOTH" $LABEL_SMOOTH +echo "[run] BASE_LEARNING_RATE" $BASE_LEARNING_RATE +echo "[run] WARMUP_EPOCHS" $WARMUP_EPOCHS +echo "[run] USE_MLPERF" $USE_MLPERF +echo "[run] NO_EVAL" $NO_EVAL +echo "[run] STOP_THRESHOLD" $STOP_THRESHOLD +echo "[run] LR_MOMENTUM" $LR_MOMENTUM +echo "[run] EVAL_OFFSET_EPOCHS" $EVAL_OFFSET_EPOCHS +echo "[run] LARS_DECAY_EPOCHS" $LARS_DECAY_EPOCHS +echo "[run] SYNTHETIC_DATA" $SYNTHETIC_DATA + +if [[ ! -z $USE_HOROVOD ]] && [[ $CPU_BIND_TYPE == "numa" ]]; then + LOCAL_SNC_VALUE=$(( OMPI_COMM_WORLD_LOCAL_RANK )) + if [[ $HLS_TYPE == "HLS2" ]]; then + export NUMA_MAPPING_DIR=$BASE_PATH + bash list_affinity_topology_bare_metal.sh + CPU_RANGE=`cat $NUMA_MAPPING_DIR/.habana_moduleID$LOCAL_SNC_VALUE` + fi + LD_PRELOAD=${PRELOAD_PATH} numactl --physcpubind=${CPU_RANGE} ${TRAIN_COMMAND} +else + LD_PRELOAD=${PRELOAD_PATH} ${TRAIN_COMMAND} +fi diff --git a/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/scripts/unpack_imagenet.sh b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/scripts/unpack_imagenet.sh new file mode 100644 index 0000000000000000000000000000000000000000..41e31e72d96f48245ad88b9ed200f4fe34efee16 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/scripts/unpack_imagenet.sh @@ -0,0 +1,164 @@ +#!/bin/bash +############################################################################### +# Copyright (c) 2023, Habana Labs Ltd. All rights reserved. +############################################################################### + +function print_synopsis() +{ + cat << HEREDOC + + Usage: $program -ta|--train-archive PATH -va|--validation-archive PATH + -o|--output-path PATH [-j|--jobs-number COUNT] [-h|--help] + + Required arguments: + -ta, --train-archive PATH path to ImageNet training archive + -va, --validation-archive PATH path to ImageNet validation archive + -o, --output-path PATH path to folder where ImageNet will be upacked + + Optional arguments: + -j, --jobs-number COUNT number of jobs used when unpacking training archive + default value is 16 + -h, --help print this help message + +HEREDOC +} + +function parse_args() +{ + export TRAIN_ARCHIVE_PATH="" + export VAL_ARCHIVE_PATH="" + export OUTPUT_PATH="" + export JOBS_NUMBER=16 + + while [ -n "$1" ]; do + case "$1" in + -ta | --train-archive ) + export TRAIN_ARCHIVE_PATH=$2 + shift 2 + ;; + -va | --validation-archive ) + export VAL_ARCHIVE_PATH=$2 + shift 2 + ;; + -o | --output-path ) + export OUTPUT_PATH=$2 + shift 2 + ;; + -j | --jobs-number ) + export JOBS_NUMBER=$2 + shift 2 + ;; + -h | --help ) + print_synopsis + exit 0 + ;; + * ) + echo "error: invalid parameter: $1" + print_synopsis + exit 1 + ;; + esac + done + + if [[ ! -f "$TRAIN_ARCHIVE_PATH" ]]; then + echo "Please specify correct path to traing archive using -ta, --train-archive." + print_synopsis + exit 1 + fi + + if [[ ! -f "$VAL_ARCHIVE_PATH" ]]; then + echo "Please specify correct path to validation archive using -va, --validation-archive." + print_synopsis + exit 1 + fi + + if [[ -z "$OUTPUT_PATH" ]]; then + echo "Please specify output path using -o, --output-path." + print_synopsis + exit 1 + fi +} + +function reset_folder() +{ + rm -rf $1 + mkdir -p $1 +} + +function upack_train_subarchive() +{ + ARCHIVE_NAME=$1 + ARCHIVE_INDEX=$2 + NO_OF_ARCHIVES=$3 + PRINT="$ARCHIVE_INDEX/$NO_OF_ARCHIVES: $ARCHIVE_NAME" + echo "Upacking $PRINT." + + pushd $TRAIN_PATH > /dev/null + + DIR=`basename $ARCHIVE_NAME .tar` + mkdir $DIR + tar xf $ARCHIVE_NAME -C $DIR + rm $ARCHIVE_NAME + + popd > /dev/null + echo "Finished upacking $PRINT." +} + +function unpack_train() +{ + export TRAIN_PATH="$OUTPUT_PATH/train" + export TMP_PATH="$OUTPUT_PATH/tmp" + reset_folder $TRAIN_PATH + reset_folder $TMP_PATH + + echo "Unpacking training data." + tar xf $TRAIN_ARCHIVE_PATH -C $TMP_PATH + + echo "Unpacking subarchives." + pushd $TMP_PATH > /dev/null + ARCHIVES_COUNT=$(ls *.tar | wc -l) + ARCHIVE_IDX=0 + for ARCHIVE in *.tar; do + ((ARCHIVE_IDX++)) + + while : ; do + JOBS_COUNT=$(ls $TRAIN_PATH/*.tar 2> /dev/null | wc -l) + if [ "$JOBS_COUNT" -lt "$JOBS_NUMBER" ]; then + break + fi + sleep 1s + done + + mv $ARCHIVE $TRAIN_PATH/ + upack_train_subarchive $ARCHIVE $ARCHIVE_IDX $ARCHIVES_COUNT & + done + popd > /dev/null + + wait + rm -rf $TMP_PATH + echo "Imagenet training data ready." +} + +function unpack_val() +{ + export VAL_PATH="$OUTPUT_PATH/val" + reset_folder $VAL_PATH + + echo "Unpacking validation data." + tar xf $VAL_ARCHIVE_PATH -C $VAL_PATH + + echo "Reorganizing validation folder." + export VALPREP_ADDR=https://raw.githubusercontent.com/soumith/imagenetloader.torch/master/valprep.sh + pushd $VAL_PATH > /dev/null + wget -qO- $VALPREP_ADDR | bash + popd > /dev/null + + echo "Imagenet validation data ready." +} + +parse_args "$@" + +unpack_train & +unpack_val & + +wait