applied-ai-018 commited on
Commit
a7fa264
·
verified ·
1 Parent(s): b92a520

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/HLS-Gaudi2-TF/defaults.cfg +40 -0
  2. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/HLS-Gaudi2-TF/launch_bert_hvd.sh +611 -0
  3. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/HLS-Gaudi2-TF/run.sh +164 -0
  4. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/bf16_config/bert.json +57 -0
  5. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/common.py +37 -0
  6. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/debug.py +132 -0
  7. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/horovod_helpers_gpu.py +23 -0
  8. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/modeling/performance.py +56 -0
  9. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/modeling/tf_utils.py +175 -0
  10. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/tb_utils.py +259 -0
  11. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/utils.py +105 -0
  12. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/README.md +97 -0
  13. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/__init__.py +0 -0
  14. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/_base.py +163 -0
  15. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/_conventions.py +54 -0
  16. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/_device.py +85 -0
  17. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/core.py +133 -0
  18. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/guidelines.md +65 -0
  19. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/misc/callstack_sampler.py +62 -0
  20. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/testing/__init__.py +0 -0
  21. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/testing/benchmark_wrappers.py +83 -0
  22. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/LICENSE +30 -0
  23. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/mlperf_variable_map.json +163 -0
  24. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/model/__init__.py +1 -0
  25. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/model/optimizer.py +59 -0
  26. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/ops_fp32_Resnet.txt +5 -0
  27. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/requirements.txt +4 -0
  28. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/debug.py +107 -0
  29. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/modeling/__init__.py +0 -0
  30. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/modeling/performance.py +56 -0
  31. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/tb_utils.py +357 -0
  32. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/__init__.py +14 -0
  33. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/controller.py +395 -0
  34. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/grad_utils.py +143 -0
  35. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/runnable.py +79 -0
  36. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/standard_runnable.py +183 -0
  37. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/utils.py +344 -0
  38. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/__init__.py +0 -0
  39. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/common.py +523 -0
  40. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/mlp_log.py +57 -0
  41. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/mlperf_variable_map.json +163 -0
  42. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/requirements.txt +7 -0
  43. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/resnet_ctl_imagenet_main.py +406 -0
  44. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/resnet_model.py +323 -0
  45. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/resnet_runnable.py +545 -0
  46. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/utils/__init__.py +0 -0
  47. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/utils/optimizers/keras/backward_compatibility.py +9 -0
  48. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/utils/optimizers/keras/lars_optimizer.py +225 -0
  49. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/utils/optimizers/keras/lars_util.py +183 -0
  50. docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/__init__.py +0 -0
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/HLS-Gaudi2-TF/defaults.cfg ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ DATESTAMP=`date +'%y%m%d%H%M%S'`
3
+ export INPUT_FILES_DIR_UNPACKED=/root/datasets/tensorflow_bert/unpacked_data
4
+ export INPUT_FILES_DIR_PACKED=/root/datasets/tensorflow_bert/packed_data_500
5
+ export EVAL_FILES_DIR=/root/datasets/tensorflow_bert/eval_dataset
6
+ export INITIAL_CHECKPOINT=/root/datasets/tensorflow_bert/checkpoint/model.ckpt-28252
7
+ export BERT_CONFIG_DIR=/root/datasets/tensorflow_bert/checkpoint
8
+ export OUTPUT_DIR=/tmp/bert_pretrain/phase_2
9
+ export LOG_DIR=/tmp/bert_pretrain/phase_2
10
+ export TRAIN_BATCH_SIZE=28
11
+ export EVAL_BATCH_SIZE=125
12
+ export MAX_EVAL_STEPS=10
13
+ export NUM_DIST_EVAL_WORKERS=8
14
+ export TRAIN_STEPS=6700
15
+ export WARMUP_STEPS=0
16
+ export LEARNING_RATE=0.000425
17
+ export LAMB_BETA_1=0.9
18
+ export LAMB_BETA_2=0.999
19
+ export EPSILON=1e-06
20
+ export LAMB_WEIGHT_DECAY_RATE=0.01
21
+ export LAMB_LEARNING_RATE_DECAY_POLY_POWER=1.0
22
+ export NUM_ACCUMULATION_STEPS=2
23
+ export SAMPLES_START_EVAL=0
24
+ export SAVE_CHECKPOINTS_STEPS=335
25
+ export PACKED_DATA=True
26
+ export USE_HOROVOD=True
27
+ export HLS_TYPE="HLS2"
28
+ export NUM_WORKERS_TOTAL=8
29
+ export TF_CPU_RUNTIME_FALLBACK=forbid
30
+ export TF_HCCL_MEMORY_ALLOWANCE_MB=1536
31
+ export HABANA_INITIAL_WORKSPACE_SIZE_MB=4600
32
+ export CPU_BIND_TYPE=cpu
33
+ export USE_LIGHTWEIGHT_CHECKPOINT=True
34
+ export DO_TRAIN=True
35
+ export DO_EVAL=True
36
+ export USE_ASYNC_CHECKPOINTING=True
37
+ export EXPERIMENTAL_SLACK=True
38
+ export SIGNALING_FROM_GRAPH=0
39
+
40
+ unset MPI_TCP_INCLUDE
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/HLS-Gaudi2-TF/launch_bert_hvd.sh ADDED
@@ -0,0 +1,611 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ DEBUG=${DEBUG:-0}
4
+ if [[ $DEBUG -eq 1 ]]; then
5
+ set -x
6
+ env
7
+ fi
8
+
9
+ # Basic paths
10
+ SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
11
+ export BASE_PATH="$( cd "$(dirname "$(readlink -f ${SCRIPT_DIR}/defaults.cfg)" )" && pwd)"
12
+ exit_code=0
13
+
14
+ OMPI_PREFIX=$(which mpirun)
15
+ export OMPI_PREFIX=$(dirname $(dirname ${OMPI_PREFIX}) )
16
+
17
+ function help()
18
+ {
19
+ echo "Usage:"
20
+ echo "$0 [ -key1 value1 -key2 value2 .... -keyn valuen ]"
21
+ echo "-c | --config Configuration file path (defaults to ./defaults.cfg)"
22
+ echo "-hf | --hostfile Host file path, 'localhost' is used if no file is provided"
23
+ echo "-u | --use_horovod Enable (0) or disable (1) horovod use"
24
+ echo "-ws | --warmup_steps"
25
+ echo "-lr | --learning_rate"
26
+ echo "-st | --stop_threshold"
27
+ echo "-acs | --num_accumul_steps"
28
+ echo "-tbs | --train_batchsize"
29
+ echo "-ebs | --eval_batchsize"
30
+ echo "-ts | --train_steps"
31
+ echo "-lb1 | --lamb_beta_1"
32
+ echo "-lb2 | --lamb_beta_2"
33
+ echo "-ep | --epsilon"
34
+ echo "-lwd | --lamb_weight_decay_rate"
35
+ echo "-ldp | --lamb_lr_decay_poly_power"
36
+ echo "-sbe | --samples_btw_eval"
37
+ echo "-sse | --samples_start_eval"
38
+ echo "-mes | --max_eval_steps"
39
+ echo "-w | --num_workers_total"
40
+ echo "-p | --packed_data Packed (0) or unpacked (1)"
41
+ echo "-sch | --save_checkpoints_steps"
42
+ echo "-cpu | --cpu_bind_type [ none | cpu | numa ]"
43
+ echo "-inputf | --input_files_dir"
44
+ echo "-evalf | --eval_files_dir"
45
+ echo "-od | --output_dir"
46
+ echo "-ckpt | --initial_checkpoint"
47
+ echo "-config | --config_dir"
48
+ echo "-hls | --hls_type"
49
+ echo "-tcp | --mpi_tcp_include"
50
+ echo "-dram | --use_dram_output"
51
+ echo "-lw | --light_weight"
52
+ echo "-lwi | --light_weight_impl [ basic (default) | sharded ]"
53
+ echo "-ac | --async_checkpointing"
54
+ echo "-ld | --log_dir"
55
+ echo "--do_train"
56
+ echo "--do_eval"
57
+ echo "--experimental_slack"
58
+ echo "-ndew | --num_dist_eval_workers Number of workers participating in distributed evaluation"
59
+ echo "-opt | --optimizer Type of optimizer, available options: 'lamb', 'sharded_lamb', 'adam'"
60
+ echo "-sfg | --signaling_from_graph Enable (1) or disable (0) SFG optimization."
61
+ }
62
+ #echo "-sws | --start_warmup_steps"
63
+
64
+ # Parse command line options
65
+ unset __config
66
+ unset __hostfile
67
+ unset __use_horovod
68
+ unset __warmup_steps
69
+ unset __learning_rate
70
+ unset __stop_threshold
71
+ unset __num_accumul_steps
72
+ unset __train_batchsize
73
+ unset __eval_batchsize
74
+ unset __train_steps
75
+ #unset __start_warmup_steps
76
+ unset __lamb_beta_1
77
+ unset __lamb_beta_2
78
+ unset __epsilon
79
+ unset __lamb_weight_decay_rate
80
+ unset __lamb_lr_decay_poly_power
81
+ unset __samples_btw_eval
82
+ unset __samples_start_eval
83
+ unset __max_eval_steps
84
+ unset __num_workers_total
85
+ unset __packed_data
86
+ unset __save_checkpoints_steps
87
+ unset __cpu_bind_type
88
+ unset __input_files_dir
89
+ unset __eval_files_dir
90
+ unset __output_dir
91
+ unset __initial_checkpoint
92
+ unset __config_dir
93
+ unset __hls_type
94
+ unset __mpi_tcp_include
95
+ unset __use_dram_output
96
+ unset __light_weight
97
+ unset __light_weight_impl
98
+ unset __async_checkpointing
99
+ unset __log_dir
100
+ unset __do_train
101
+ unset __do_eval
102
+ unset __experimental_slack
103
+ unset __num_dist_eval_workers
104
+ unset __optimizer
105
+ unset __aux_scirpt_params
106
+ unset __ssh_port
107
+ unset __signaling_from_graph
108
+
109
+ while [ -n "$1" ]; do
110
+ case $1 in
111
+ -c | --config )
112
+ shift
113
+ __config=$1
114
+ ;;
115
+ -hf | --hostfile)
116
+ shift
117
+ __hostfile=$1
118
+ ;;
119
+ -u | --use_horovod )
120
+ shift
121
+ __use_horovod=$1
122
+ ;;
123
+ -ws | --warmup_steps )
124
+ shift
125
+ __warmup_steps=$1
126
+ ;;
127
+ -lr | --learning_rate )
128
+ shift
129
+ __learning_rate=$1
130
+ ;;
131
+ -st | --stop_threshold )
132
+ shift
133
+ __stop_threshold=$1
134
+ ;;
135
+ -acs | --num_accumul_steps )
136
+ shift
137
+ __num_accumul_steps=$1
138
+ ;;
139
+ -tbs | --train_batchsize )
140
+ shift
141
+ __train_batchsize=$1
142
+ ;;
143
+ -ebs | --eval_batchsize)
144
+ shift
145
+ __eval_batchsize=$1
146
+ ;;
147
+ -ts | --train_steps)
148
+ shift
149
+ __train_steps=$1
150
+ ;;
151
+ -lb1 | --lamb_beta_1)
152
+ shift
153
+ __lamb_beta_1=$1
154
+ ;;
155
+ -lb2 | --lamb_beta_2)
156
+ shift
157
+ __lamb_beta_2=$1
158
+ ;;
159
+ -ep | --epsilon)
160
+ shift
161
+ __epsilon=$1
162
+ ;;
163
+ -lwd | --lamb_weight_decay_rate)
164
+ shift
165
+ __lamb_weight_decay_rate=$1
166
+ ;;
167
+ -ldp | --lamb_lr_decay_poly_power)
168
+ shift
169
+ __lamb_lr_decay_poly_power=$1
170
+ ;;
171
+ -sbe | --samples_btw_eval)
172
+ shift
173
+ __samples_btw_eval=$1
174
+ ;;
175
+ -sse | --samples_start_eval)
176
+ shift
177
+ __samples_start_eval=$1
178
+ ;;
179
+ -mes | --max_eval_steps)
180
+ shift
181
+ __max_eval_steps=$1
182
+ ;;
183
+ -w | --num_workers_total)
184
+ shift
185
+ __num_workers_total=$1
186
+ ;;
187
+ -p | --packed_data)
188
+ shift
189
+ __packed_data=$1
190
+ ;;
191
+ -sch | --save_checkpoints_steps)
192
+ shift
193
+ __save_checkpoints_steps=$1
194
+ ;;
195
+ -cpu | --cpu_bind_type)
196
+ shift
197
+ __cpu_bind_type=$1
198
+ case ${__cpu_bind_type} in
199
+ numa | cpu | none )
200
+ ;;
201
+ *)
202
+ echo "--cpu-pin must be one of the following numa | cpu | none "
203
+ exit 1
204
+ esac
205
+ ;;
206
+ -inputf | --input_files_dir)
207
+ shift
208
+ __input_files_dir=$1
209
+ ;;
210
+ -sfg | --signaling_from_graph)
211
+ shift
212
+ __signaling_from_graph=$1
213
+ ;;
214
+ -evalf | --eval_files_dir)
215
+ shift
216
+ __eval_files_dir=$1
217
+ ;;
218
+ -od | --output_dir)
219
+ shift
220
+ __output_dir=$1
221
+ ;;
222
+ -ckpt | --initial_checkpoint)
223
+ shift
224
+ __initial_checkpoint=$1
225
+ ;;
226
+ -config | --config_dir)
227
+ shift
228
+ __config_dir=$1
229
+ ;;
230
+ -hls | --hls_type)
231
+ shift
232
+ __hls_type=$1
233
+ ;;
234
+ -tcp | --mpi_tcp_include)
235
+ shift
236
+ __mpi_tcp_include=$1
237
+ ;;
238
+ -dram | --use_dram_output)
239
+ shift
240
+ __use_dram_output=$1
241
+ ;;
242
+ -lw | --light_weight)
243
+ shift
244
+ __light_weight=$1
245
+ ;;
246
+ -lwi | --light_weight_impl)
247
+ shift
248
+ __light_weight_impl=$1
249
+ ;;
250
+ -ac | --async_checkpointing)
251
+ shift
252
+ __async_checkpointing=$1
253
+ ;;
254
+ -ld | --log_dir)
255
+ shift
256
+ __log_dir=$1
257
+ ;;
258
+ --do_train)
259
+ shift
260
+ __do_train=$1
261
+ ;;
262
+ --do_eval)
263
+ shift
264
+ __do_eval=$1
265
+ ;;
266
+ --experimental_slack)
267
+ shift
268
+ __experimental_slack=$1
269
+ ;;
270
+ -ndew | --num_dist_eval_workers)
271
+ shift
272
+ __num_dist_eval_workers=$1
273
+ ;;
274
+ -opt | --optimizer)
275
+ shift
276
+ __optimizer=$1
277
+ ;;
278
+ -port | --ssh_port)
279
+ shift
280
+ __ssh_port=$1
281
+ ;;
282
+ -h | --help)
283
+ help
284
+ exit 1
285
+ ;;
286
+ * )
287
+ __aux_param=$1
288
+ shift
289
+ echo "The parameter $1 will be passed directly to python script"
290
+ __aux_scirpt_params="${__aux_scirpt_params}:${__aux_param}=${1}"
291
+ ;;
292
+ esac
293
+ shift
294
+ done
295
+
296
+ export CFG_FILE=${__config:-"${BASE_PATH}/defaults.cfg"}
297
+ if [[ -f ${CFG_FILE} ]]; then
298
+ source ${CFG_FILE}
299
+ else
300
+ echo "Could not find ${CFG_FILE}"
301
+ exit 1
302
+ fi
303
+
304
+ # Set default values for environmental variable
305
+ export HOST_FILE=${__hostfile:-"${OMPI_MCA_orte_default_hostfile}"}
306
+ export SSH_PORT=${__ssh_port:-"3022"}
307
+
308
+ if [[ -z "${HABANA_LOGS}" ]]; then
309
+ export HABANA_LOGS="/var/logs/habana_logs"
310
+ echo "Creating default directory for habana_logs."
311
+ mkdir -p $HABANA_LOGS
312
+ fi
313
+ export EVAL_FILES_DIR=${EVAL_FILES_DIR}
314
+ export OUTPUT_DIR=${OUTPUT_DIR}
315
+ export PHASE1_CKPT=${INITIAL_CHECKPOINT}
316
+ export INITIAL_CHECKPOINT=${INITIAL_CHECKPOINT}
317
+ export BERT_CONFIG_DIR=${BERT_CONFIG_DIR}
318
+ export NUM_WORKERS_PER_HLS=${NUM_WORKERS_PER_HLS}
319
+ export OPTIMIZE_DMA_ENGINES_ALLOCATION=${OPTIMIZE_DMA_ENGINES_ALLOCATION}
320
+ export TF_CPU_RUNTIME_FALLBACK=${TF_CPU_RUNTIME_FALLBACK}
321
+ export TF_HCCL_MEMORY_ALLOWANCE_MB=${TF_HCCL_MEMORY_ALLOWANCE_MB}
322
+ export HABANA_INITIAL_WORKSPACE_SIZE_MB=${HABANA_INITIAL_WORKSPACE_SIZE_MB}
323
+
324
+ # Override defaults with command line options if needed
325
+ export MPI_TCP_INCLUDE=${__mpi_tcp_include:-$MPI_TCP_INCLUDE}
326
+ export USE_HOROVOD=${__use_horovod:-$USE_HOROVOD}
327
+ export WARMUP_STEPS=${__warmup_steps:-$WARMUP_STEPS}
328
+ export LEARNING_RATE=${__learning_rate:-$LEARNING_RATE}
329
+ export STOP_THRESHOLD=${__stop_threshold:-$STOP_THRESHOLD}
330
+ export NUM_ACCUMULATION_STEPS=${__num_accumul_steps:-$NUM_ACCUMULATION_STEPS}
331
+ export TRAIN_BATCH_SIZE=${__train_batchsize:-$TRAIN_BATCH_SIZE}
332
+ export EVAL_BATCH_SIZE=${__eval_batchsize:-$EVAL_BATCH_SIZE}
333
+ export TRAIN_STEPS=${__train_steps:-$TRAIN_STEPS}
334
+ export LAMB_BETA_1=${__lamb_beta_1:-$LAMB_BETA_1}
335
+ export LAMB_BETA_2=${__lamb_beta_2:-$LAMB_BETA_2}
336
+ export EPSILON=${__epsilon:-$EPSILON}
337
+ export LAMB_WEIGHT_DECAY_RATE=${__lamb_weight_decay_rate:-$LAMB_WEIGHT_DECAY_RATE}
338
+ export LAMB_LEARNING_RATE_DECAY_POLY_POWER=${__lamb_lr_decay_poly_power:-$LAMB_LEARNING_RATE_DECAY_POLY_POWER}
339
+ export SAMPLES_START_EVAL=${__samples_start_eval:-$SAMPLES_START_EVAL}
340
+ export MAX_EVAL_STEPS=${__max_eval_steps:-$MAX_EVAL_STEPS}
341
+ export NUM_WORKERS_TOTAL=${__num_workers_total:-$NUM_WORKERS_TOTAL}
342
+ export PACKED_DATA=${__packed_data:-$PACKED_DATA}
343
+ export SAVE_CHECKPOINTS_STEPS=${__save_checkpoints_steps:-$SAVE_CHECKPOINTS_STEPS}
344
+ SAMPLES_BETWEEN_EVAL=$(($TRAIN_BATCH_SIZE*$NUM_WORKERS_TOTAL*$NUM_ACCUMULATION_STEPS*$SAVE_CHECKPOINTS_STEPS))
345
+ export SAMPLES_BETWEEN_EVAL=${__samples_btw_eval:-$SAMPLES_BETWEEN_EVAL}
346
+ export CPU_BIND_TYPE=${__cpu_bind_type:-$CPU_BIND_TYPE}
347
+ export EVAL_FILES_DIR=${__eval_files_dir:-$EVAL_FILES_DIR}
348
+ export SIGNALING_FROM_GRAPH=${__signaling_from_graph:-$SIGNALING_FROM_GRAPH}
349
+ export OUTPUT_DIR=${__output_dir:-$OUTPUT_DIR}
350
+ export PHASE1_CKPT=${__initial_checkpoint:-$INITIAL_CHECKPOINT}
351
+ export BERT_CONFIG_DIR=${__config_dir:-$BERT_CONFIG_DIR}
352
+ export HLS_TYPE=${__hls_type:-$HLS_TYPE}
353
+ export USE_DRAM_OUTPUT=${__use_dram_output:-"True"}
354
+ export USE_LIGHTWEIGHT_CHECKPOINT=${__light_weight:-$USE_LIGHTWEIGHT_CHECKPOINT}
355
+ export LIGHTWEIGHT_CHECKPOINT_IMPL=${__light_weight_impl:-"basic"}
356
+ export USE_ASYNC_CHECKPOINTING=${__async_checkpointing:-$USE_ASYNC_CHECKPOINTING}
357
+ export LOG_DIR=${__log_dir:-$LOG_DIR}
358
+ export DO_TRAIN=${__do_train:-$DO_TRAIN}
359
+ export DO_EVAL=${__do_eval:-$DO_EVAL}
360
+ export EXPERIMENTAL_SLACK=${__experimental_slack:-$EXPERIMENTAL_SLACK}
361
+ export NUM_DIST_EVAL_WORKERS=${__num_dist_eval_workers:-$NUM_DIST_EVAL_WORKERS}
362
+ export AUX_PARAMS=${__aux_scirpt_params:-$AUX_PARAMS}
363
+ export OPTIMIZER=${__optimizer:-$OPTIMIZER}
364
+
365
+ if [[ "$HLS_TYPE" == "HLS2" ]]; then
366
+ export NUM_WORKERS_PER_HLS=8
367
+ else
368
+ "============== WRONG HLS TYPE!! ==============="
369
+ exit -1
370
+ fi
371
+
372
+ if [ "$PACKED_DATA" == "False" ]; then
373
+ export INPUT_FILES_DIR=${__input_files_dir:-$INPUT_FILES_DIR_UNPACKED}
374
+ else
375
+ export INPUT_FILES_DIR=${__input_files_dir:-$INPUT_FILES_DIR_PACKED}
376
+ fi
377
+
378
+ if [ "$USE_HOROVOD" == "True" ]; then
379
+ export HOROVOD_STALL_CHECK_DISABLE=1
380
+ echo HOROVOD_STALL_CHECK_DISABLE=$HOROVOD_STALL_CHECK_DISABLE
381
+
382
+ # SAO:ON by default
383
+ export TF_DISABLE_SCOPED_ALLOCATOR=${TF_DISABLE_SCOPED_ALLOCATOR:-False}
384
+ echo TF_DISABLE_SCOPED_ALLOCATOR=$TF_DISABLE_SCOPED_ALLOCATOR
385
+ fi
386
+
387
+ function getmulti_hls_ips()
388
+ {
389
+ multi_hcl_ip="MULTI_HLS_IPS="
390
+ hostsFile=$1
391
+ firstHost=1
392
+ hostCount=0
393
+
394
+ # iterate over non-empty and non-commented lines
395
+ for h in $(cat $hostsFile | sed '/^$/d' | grep -v '^#'); do
396
+ if [[ $firstHost -eq 1 ]]; then
397
+ firstHost=0
398
+ else
399
+ multi_hcl_ip+=","
400
+ fi
401
+ multi_hcl_ip+=$h
402
+ hostCount=$((hostCount + 1))
403
+ done
404
+
405
+ echo "[getmulti_hls_ips] Host Count : $hostCount"
406
+ echo "[getmulti_hls_ips] Exporting : $multi_hcl_ip"
407
+ export $multi_hcl_ip
408
+ }
409
+
410
+
411
+ function run_per_ip()
412
+ {
413
+ if [ -n "$OMPI_COMM_WORLD_SIZE" ]; then
414
+ 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."
415
+ exit 1
416
+ fi
417
+ _cmd="$@"
418
+ # Due to technical difficulties with the following solution, the _cmd stderr shall be redirected to stdout.
419
+ if [[ -z ${MULTI_HLS_IPS} ]]; then
420
+ echo "[launch_bert_hvd] MULTI_HLS_IPS undefined - maybe a missing /root/shared/hosts file?"
421
+ exit -1
422
+ else
423
+ if [ -n "$MPI_TCP_INCLUDE" ]; then
424
+ _option_btl_tcp_if_include="--mca btl_tcp_if_include ${MPI_TCP_INCLUDE}"
425
+ else
426
+ _option_btl_tcp_if_include=""
427
+ fi
428
+ mpirun --allow-run-as-root \
429
+ --mca plm_rsh_args -p${SSH_PORT} \
430
+ ${_option_btl_tcp_if_include} \
431
+ --tag-output \
432
+ --merge-stderr-to-stdout \
433
+ --prefix ${OMPI_PREFIX} \
434
+ -H ${MULTI_HLS_IPS} \
435
+ bash -c "`declare`; `declare -x`; ($_cmd 2>&1)" 2>/dev/null
436
+ fi
437
+ }
438
+
439
+ export MULTI_HLS_IPS=localhost
440
+ if [[ -f ${HOST_FILE} ]]; then
441
+ getmulti_hls_ips ${HOST_FILE}
442
+ fi
443
+
444
+ # Create recipes directory if it does not exist and adjust dirctory name
445
+ # if we are collecting traces - which require debug information
446
+ run_per_ip mkdir -p ${OUTPUT_DIR} # 2>/dev/null
447
+ run_per_ip rm -rf ${OUTPUT_DIR}/* # 2>/dev/null
448
+ run_per_ip mkdir -p ${LOG_DIR}
449
+ mkdir -p ${LOG_DIR}
450
+
451
+ run_per_ip pip install -r $BASE_PATH/../TensorFlow/nlp/bert/requirements.txt
452
+
453
+ #run_per_ip rm -rf /tmp/checkpoint /tmp/eval /tmp/events.out.tfevents.* /tmp/graph.pbtxt /tmp/model.ckpt-*
454
+ #run_per_ip rm -rf /tmp/rank_*/checkpoint /tmp/rank_*/eval /tmp/rank_*/events.out.tfevents.* /tmp/rank_*/graph.pbtxt /tmp/rank_*/model.ckpt-*
455
+
456
+ function setup_libjemalloc()
457
+ {
458
+ local libjemalloc_1_lib="libjemalloc.so.1"
459
+ local libjemalloc_2_lib="libjemalloc.so.2"
460
+ local is_v2_not_present=`LD_PRELOAD=${libjemalloc_2_lib} head -0 2>&1 > /dev/null`
461
+
462
+ if [ -z "${is_v2_not_present}" ]; then
463
+ export LD_PRELOAD=${libjemalloc_2_lib}:$LD_PRELOAD
464
+ else
465
+ export LD_PRELOAD=${libjemalloc_1_lib}:$LD_PRELOAD
466
+ fi
467
+ }
468
+ run_per_ip setup_libjemalloc
469
+
470
+ if [[ -z ${MULTI_HLS_IPS} ]]; then
471
+ echo "[launch_bert_hvd] MULTI_HLS_IPS undefined - maybe a missing /root/shared/hosts file?"
472
+ exit -1
473
+ else
474
+ IFS=',' read -ra IPS <<< "$MULTI_HLS_IPS"
475
+ let MPI_NP=${#IPS[@]}*${NUM_WORKERS_PER_HLS}
476
+ export NUM_WORKERS_TOTAL=${NUM_WORKERS_TOTAL:-$MPI_NP}
477
+
478
+ if [[ $NUM_WORKERS_TOTAL != $MPI_NP ]]; then
479
+ echo $NUM_WORKERS_TOTAL $MPI_NP
480
+ echo "=============== WRONG NUMBER_WORKERS_TOTAL!! ==============="
481
+ exit -1
482
+ fi
483
+
484
+ echo NUM_WORKERS_TOTAL=$NUM_WORKERS_TOTAL
485
+
486
+ function generate_mpi_hostfile()
487
+ {
488
+ echo "Generating MPI hostfile..."
489
+ local num_nodes=${2:-8}
490
+ local file_name="hostfile"
491
+ export MPI_HOSTFILE_PATH=$1/${file_name}
492
+
493
+ rm -rf ${MPI_HOSTFILE_PATH}
494
+ echo "PATH: ${MPI_HOSTFILE_PATH}"
495
+ touch ${MPI_HOSTFILE_PATH}
496
+
497
+ IFS=',' read -ra IPS <<< "$MULTI_HLS_IPS"
498
+ for i in "${IPS[@]}"; do
499
+ echo "$i slots=${num_nodes}" >> ${MPI_HOSTFILE_PATH}
500
+ done
501
+ echo "Config: "
502
+ cat ${MPI_HOSTFILE_PATH}
503
+ }
504
+
505
+ generate_mpi_hostfile ${OUTPUT_DIR} ${NUM_WORKERS_PER_HLS}
506
+
507
+ export testdate=`date +%Y-%m-%d`
508
+ export testtime=`date +%H%M%S`
509
+ export OUTPUT_DIR=${__output_dir:-/root/scratch/bert/bert_gaudi${NUM_WORKERS_TOTAL}_${testdate}_${testtime}}
510
+
511
+ run_per_ip mkdir -p ${OUTPUT_DIR}
512
+
513
+ run_per_ip rm -f $LOG_DIR/result_*
514
+ run_per_ip rm -f ${LOG_DIR}/tf_bert_pretraining_lamb.log
515
+
516
+ LOGFILE=$LOG_DIR/tf_bert_pretraining_lamb.log
517
+ export TF_RECIPE_CACHE_PATH=/tmp/bert_pretrain/phase_2
518
+ run_per_ip mkdir -p $TF_RECIPE_CACHE_PATH
519
+
520
+ MPI_MAP_BY=socket
521
+ MPI_MAP_BY_PE=`lscpu | grep "^CPU(s):"| awk -v NUM=${NUM_WORKERS_PER_HLS} '{print int($2/NUM/2)}'`
522
+ if [[ "$CPU_BIND_TYPE" == "numa" || "$CPU_BIND_TYPE" == "none" ]]; then
523
+ MPIRUN_ARGS_MAP_BY_PE="-bind-to none"
524
+ else
525
+ MPIRUN_ARGS_MAP_BY_PE="--bind-to core --map-by $MPI_MAP_BY:PE=$MPI_MAP_BY_PE"
526
+ fi
527
+
528
+ if [ -n "$MPI_TCP_INCLUDE" ]; then
529
+ _option_btl_tcp_if_include="--mca btl_tcp_if_include ${MPI_TCP_INCLUDE}"
530
+ else
531
+ _option_btl_tcp_if_include=""
532
+ fi
533
+
534
+ TRAINING_COMMAND="mpirun --allow-run-as-root \
535
+ --display-map \
536
+ --report-bindings \
537
+ --bind-to none \
538
+ -np ${NUM_WORKERS_TOTAL}\
539
+ --hostfile ${MPI_HOSTFILE_PATH} \
540
+ --prefix ${OMPI_PREFIX} \
541
+ --mca plm_rsh_args -p${SSH_PORT} \
542
+ ${_option_btl_tcp_if_include} \
543
+ --merge-stderr-to-stdout \
544
+ --tag-output \
545
+ --output-filename ${LOG_DIR}/bert_log \
546
+ -x USE_HOROVOD=${USE_HOROVOD} \
547
+ -x TF_MODULES_RELEASE_BUILD=/usr/lib/habanalabs/ \
548
+ -x HABANA_LOGS=${HABANA_LOGS} \
549
+ -x LEARNING_RATE=${LEARNING_RATE} \
550
+ -x STOP_THRESHOLD=${STOP_THRESHOLD} \
551
+ -x NUM_ACCUMULATION_STEPS=${NUM_ACCUMULATION_STEPS} \
552
+ -x TRAIN_BATCH_SIZE=${TRAIN_BATCH_SIZE} \
553
+ -x EVAL_BATCH_SIZE=${EVAL_BATCH_SIZE} \
554
+ -x TRAIN_STEPS=${TRAIN_STEPS} \
555
+ -x NUM_WORKERS_TOTAL=${NUM_WORKERS_TOTAL} \
556
+ -x WARMUP_STEPS=${WARMUP_STEPS} \
557
+ -x LAMB_BETA_1=${LAMB_BETA_1} \
558
+ -x LAMB_BETA_2=${LAMB_BETA_2} \
559
+ -x EPSILON=${EPSILON} \
560
+ -x LAMB_WEIGHT_DECAY_RATE=${LAMB_WEIGHT_DECAY_RATE} \
561
+ -x LAMB_LEARNING_RATE_DECAY_POLY_POWER=${LAMB_LEARNING_RATE_DECAY_POLY_POWER} \
562
+ -x SAMPLES_BETWEEN_EVAL=${SAMPLES_BETWEEN_EVAL} \
563
+ -x SAMPLES_START_EVAL=${SAMPLES_START_EVAL} \
564
+ -x MAX_EVAL_STEPS=${MAX_EVAL_STEPS} \
565
+ -x INPUT_FILES_DIR=${INPUT_FILES_DIR} \
566
+ -x EVAL_FILES_DIR=${EVAL_FILES_DIR} \
567
+ -x OUTPUT_DIR=${OUTPUT_DIR} \
568
+ -x PHASE1_CKPT=${PHASE1_CKPT} \
569
+ -x BERT_CONFIG_DIR=${BERT_CONFIG_DIR} \
570
+ -x OPTIMIZE_DMA_ENGINES_ALLOCATION=${OPTIMIZE_DMA_ENGINES_ALLOCATION} \
571
+ -x TF_CPU_RUNTIME_FALLBACK=${TF_CPU_RUNTIME_FALLBACK} \
572
+ -x TF_HCCL_MEMORY_ALLOWANCE_MB=${TF_HCCL_MEMORY_ALLOWANCE_MB} \
573
+ -x HABANA_INITIAL_WORKSPACE_SIZE_MB=${HABANA_INITIAL_WORKSPACE_SIZE_MB} \
574
+ -x HLS_TYPE=${HLS_TYPE} \
575
+ -x MPI_TCP_INCLUDE=${MPI_TCP_INCLUDE} \
576
+ -x SAVE_CHECKPOINTS_STEPS=${SAVE_CHECKPOINTS_STEPS} \
577
+ -x PACKED_DATA=${PACKED_DATA} \
578
+ -x TESTDATE=${testdate} \
579
+ -x TESTTIME=${testtime} \
580
+ -x CPU_BIND_TYPE=${CPU_BIND_TYPE} \
581
+ ${MPIRUN_ARGS_MAP_BY_PE} \
582
+ -x NUM_WORKERS_PER_HLS=${NUM_WORKERS_PER_HLS} \
583
+ -x USE_DRAM_OUTPUT=${USE_DRAM_OUTPUT} \
584
+ -x USE_LIGHTWEIGHT_CHECKPOINT=${USE_LIGHTWEIGHT_CHECKPOINT} \
585
+ -x LIGHTWEIGHT_CHECKPOINT_IMPL=${LIGHTWEIGHT_CHECKPOINT_IMPL} \
586
+ -x USE_ASYNC_CHECKPOINTING=${USE_ASYNC_CHECKPOINTING} \
587
+ -x LOG_DIR=${LOG_DIR} \
588
+ -x TF_RECIPE_CACHE_PATH \
589
+ -x DO_TRAIN=${DO_TRAIN} \
590
+ -x DO_EVAL=${DO_EVAL} \
591
+ -x EXPERIMENTAL_SLACK=${EXPERIMENTAL_SLACK} \
592
+ -x NUM_DIST_EVAL_WORKERS=${NUM_DIST_EVAL_WORKERS} \
593
+ -x WARMUP_STEPS=${WARMUP_STEPS}
594
+ -x AUX_PARAMS=${AUX_PARAMS} \
595
+ -x TF_ENABLE_DYNAMIC_SHAPES=${TF_ENABLE_DYNAMIC_SHAPES} \
596
+ -x OPTIMIZER=${OPTIMIZER} \
597
+ -x SIGNALING_FROM_GRAPH=${SIGNALING_FROM_GRAPH} \
598
+ ${BASE_PATH}/run.sh"
599
+
600
+ echo "TRAINING COMMAND = ${TRAINING_COMMAND}"
601
+ printf "[launch_bert_hvd] Starting training...\n\n"
602
+ time $TRAINING_COMMAND |& tee -a $LOGFILE
603
+ fi
604
+ run_per_ip rm -rf $OUTPUT_DIR/*/model.ckpt-*
605
+ rm -rf $BASE_PATH/log
606
+ cp /root/build_log.csv ${OUTPUT_DIR}/
607
+ cp ${MPI_HOSTFILE_PATH} ${OUTPUT_DIR}/
608
+ cp -r $LOG_DIR/bert_log $BASE_PATH/log
609
+ cp $TF_RECIPE_CACHE_PATH/tf_bert_pretraining* ${OUTPUT_DIR}/
610
+ chmod -R 777 ${OUTPUT_DIR}
611
+ exit $exit_code
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/HLS-Gaudi2-TF/run.sh ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #! /bin/bash
2
+
3
+ #set -x
4
+ ###############################################################################
5
+ # Copyright (C) 2020-2023 Habana Labs, Ltd. an Intel Company
6
+ #
7
+ ###############################################################################
8
+
9
+ SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
10
+ export BASE_PATH="$( cd "$(dirname "$(readlink -f ${SCRIPT_DIR}/defaults.cfg)" )" && pwd)"
11
+ export PYTHONPATH=${BASE_PATH}:${BASE_PATH}/../TensorFlow/common
12
+
13
+ PT_VERSION=`python3 -c 'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}")'`
14
+ TF_VERSION=`python3 -c "import tensorflow as tf; print(tf.__version__.replace('.', '_'))"`
15
+ PATCH_PATH=/usr/local/lib/python${PT_VERSION}/dist-packages/habana_frameworks/tensorflow/tf${TF_VERSION}/lib/habanalabs
16
+ export PYTHONPATH=${PATCH_PATH}:${PYTHONPATH}
17
+
18
+ TRAIN_BATCH_SIZE=${TRAIN_BATCH_SIZE:-7}
19
+ EVAL_BATCH_SIZE=${EVAL_BATCH_SIZE:-125}
20
+ LEARNING_RATE=${LEARNING_RATE:-5e-5}
21
+ PRECISION=${PRECISION:-fp32}
22
+ WARMUP_STEPS=${WARMUP_STEPS:-0}
23
+ TRAIN_STEPS=${TRAIN_STEPS:-8103}
24
+ SAVE_CHECKPOINTS_STEPS=${SAVE_CHECKPOINTS_STEPS:-335}
25
+ NUM_ACCUMULATION_STEPS=${NUM_ACCUMULATION_STEPS:-4}
26
+ SAMPLES_BETWEEN_EVAL=${SAMPLES_BETWEEN_EVAL:-150080}
27
+ STOP_THRESHOLD=${STOP_THRESHOLD:-0.720}
28
+ SAMPLES_START_EVAL=${SAMPLES_START_EVAL:-3000000}
29
+ MAX_EVAL_STEPS=${MAX_EVAL_STEPS:-0}
30
+ IS_DIST_EVAL_ENABLED=${IS_DIST_EVAL_ENABLED:-false}
31
+ MAX_SEQ_LENGTH=${MAX_SEQ_LENGTH:-512}
32
+ MAX_PRED_PER_SEQ=${MAX_PRED_PER_SEQ:-76}
33
+ FAST_PERF_ONLY=${FAST_PERF_ONLY:-0}
34
+ PACKED_DATA=${PACKED_DATA:-False}
35
+ TESTDATE=${TESTDATE}
36
+ TESTTIME=${TESTTIME}
37
+ LAMB_BETA_1=${LAMB_BETA_1:-0.9}
38
+ LAMB_BETA_2=${LAMB_BETA_2:-0.999}
39
+ EPSILON=${EPSILON:-1e-6}
40
+ LAMB_WEIGHT_DECAY_RATE=${LAMB_WEIGHT_DECAY_RATE:-0.01}
41
+ LAMB_LEARNING_RATE_DECAY_POLY_POWER=${LAMB_LEARNING_RATE_DECAY_POLY_POWER:-1.0}
42
+ NUM_WORKERS_PER_HLS=${NUM_WORKERS_PER_HLS:-4}
43
+ DO_TRAIN=${DO_TRAIN:-True}
44
+ DO_EVAL=${DO_EVAL:-True}
45
+ EXPERIMENTAL_SLACK=${EXPERIMENTAL_SLACK:-True}
46
+ NUM_DIST_EVAL_WORKERS=${NUM_DIST_EVAL_WORKERS:-0}
47
+ OPTIMIZER=${OPTIMIZER:-'lamb'}
48
+
49
+ export TF_BF16_CONVERSION=${BASE_PATH}/../TensorFlow/common/bf16_config/bert.json
50
+ export USE_LIGHTWEIGHT_CHECKPOINT=${USE_LIGHTWEIGHT_CHECKPOINT:-True}
51
+ export LIGHTWEIGHT_CHECKPOINT_IMPL=${LIGHTWEIGHT_CHECKPOINT_IMPL:-"basic"}
52
+ export USE_ASYNC_CHECKPOINTING=${USE_ASYNC_CHECKPOINTING:-False}
53
+ export BERT_CONFIG_FILE=${BERT_CONFIG_FILE:-${BERT_CONFIG_DIR}/bert_config.json}
54
+
55
+ if [[ $SIGNALING_FROM_GRAPH -eq 1 ]]; then
56
+ export TF_DISABLE_SCOPED_ALLOCATOR=True
57
+ export HOROVOD_FUSION_THRESHOLD=0
58
+ export TF_USE_SIGNALING_FROM_ENCAP_OP=1
59
+ else
60
+ export TF_USE_SIGNALING_FROM_ENCAP_OP=0
61
+ fi
62
+
63
+ # Currently sharded LAMB works only when ScopedAllocator is disabled and loop unrolling is False
64
+ if [ $OPTIMIZER == "sharded_lamb" ]; then
65
+ export TF_DISABLE_SCOPED_ALLOCATOR=True
66
+ AUX_PARAMS="${AUX_PARAMS} --loop_unrolling_for_train_op=False"
67
+ fi
68
+
69
+ # Under the hood, AMP (Arithmetic Mixed Precision) training is applied via TF_BF16_CONVERSION
70
+ # default precision is fp32.
71
+ precision="--noamp"
72
+
73
+ USE_HOROVOD=${USE_HOROVOD:-"False"}
74
+ if [ $USE_HOROVOD == "True" ]; then
75
+ horovod="--horovod --allreduce_post_accumulation=True"
76
+ IS_DIST_EVAL_ENABLED="True"
77
+ else
78
+ horovod=""
79
+ fi
80
+
81
+ #PHASE 1 Config
82
+ export PHASE1_CKPT=${PHASE1_CKPT:-/root/datasets/bert_pretraining/MLPerf_BERT_checkpoint/model.ckpt-28252}
83
+ export INPUT_FILES_DIR=${INPUT_FILES_DIR:-/root/datasets/bert_pretraining/training}
84
+ export EVAL_FILES_DIR=${EVAL_FILES_DIR:-/root/datasets/bert_pretraining/evaluation}
85
+
86
+ #Generate Host Folder
87
+ if [ $USE_DRAM_OUTPUT == "True" ]; then
88
+ host=$(hostname)
89
+ if [ "$OMPI_COMM_WORLD_LOCAL_RANK" == "0" ]; then
90
+ mkdir -p /mnt/dramfs
91
+ mount -t tmpfs -o size=200g tmpfs /mnt/dramfs
92
+ fi
93
+ export OUTPUT_DIR=/mnt/dramfs/bert_gaudi${NUM_WORKERS_TOTAL}_${TESTDATE}_${TESTTIME}/${host}
94
+ mkdir -p $OUTPUT_DIR
95
+ fi
96
+
97
+ # clear cache
98
+ if [[ $OMPI_COMM_WORLD_LOCAL_RANK -eq 0 ]]; then
99
+ PROC_FS=${PROC_FS:-"/proc"}
100
+ sync && echo 3 > $PROC_FS/sys/vm/drop_caches
101
+ fi
102
+
103
+ if [ $PACKED_DATA == "False" ]; then
104
+ packing_arg=""
105
+ else
106
+ packing_arg="--enable_packed_data_mode --avg_seq_per_pack=2"
107
+ fi
108
+
109
+ AUX_PARAMS=$(echo ${AUX_PARAMS} | sed s/:/\ /g)
110
+
111
+ enable_device_warmup=True
112
+
113
+ TRAIN_COMMAND="python3 ${BASE_PATH}/../TensorFlow/nlp/bert/run_pretraining.py \
114
+ --input_files_dir=$INPUT_FILES_DIR \
115
+ --init_checkpoint=$PHASE1_CKPT \
116
+ --eval_files_dir=$EVAL_FILES_DIR\
117
+ --output_dir=$OUTPUT_DIR \
118
+ --bert_config_file=$BERT_CONFIG_FILE \
119
+ --do_train=$DO_TRAIN \
120
+ --do_eval=$DO_EVAL \
121
+ --experimental_slack=$EXPERIMENTAL_SLACK \
122
+ --is_dist_eval_enabled=$IS_DIST_EVAL_ENABLED \
123
+ --train_batch_size=$TRAIN_BATCH_SIZE \
124
+ --eval_batch_size=$EVAL_BATCH_SIZE \
125
+ --max_eval_steps=$MAX_EVAL_STEPS \
126
+ --max_seq_length=$MAX_SEQ_LENGTH \
127
+ --max_predictions_per_seq=$MAX_PRED_PER_SEQ \
128
+ --num_train_steps=$TRAIN_STEPS \
129
+ --num_accumulation_steps=$NUM_ACCUMULATION_STEPS \
130
+ --num_warmup_steps=$WARMUP_STEPS \
131
+ --save_checkpoints_steps=$SAVE_CHECKPOINTS_STEPS \
132
+ --learning_rate=$LEARNING_RATE \
133
+ $horovod \
134
+ $precision \
135
+ $packing_arg \
136
+ --enable_device_warmup=$enable_device_warmup \
137
+ --samples_between_eval=$SAMPLES_BETWEEN_EVAL \
138
+ --stop_threshold=$STOP_THRESHOLD \
139
+ --samples_start_eval=$SAMPLES_START_EVAL \
140
+ --beta_1=$LAMB_BETA_1 \
141
+ --beta_2=$LAMB_BETA_2 \
142
+ --epsilon=$EPSILON \
143
+ --weight_decay_rate=$LAMB_WEIGHT_DECAY_RATE \
144
+ --power=$LAMB_LEARNING_RATE_DECAY_POLY_POWER \
145
+ --enable_habana_backend \
146
+ --dllog_path=$LOG_DIR/bert_dllog.json \
147
+ --use_lightweight_checkpoint=$USE_LIGHTWEIGHT_CHECKPOINT \
148
+ --lightweight_checkpoint_impl=$LIGHTWEIGHT_CHECKPOINT_IMPL \
149
+ --use_async_checkpointing=$USE_ASYNC_CHECKPOINTING \
150
+ --num_dist_eval_workers=$NUM_DIST_EVAL_WORKERS \
151
+ --optimizer_type=$OPTIMIZER \
152
+ ${AUX_PARAMS}
153
+ "
154
+
155
+ LD_PRELOAD=${PRELOAD_PATH} ${TRAIN_COMMAND}
156
+
157
+ if [[ $OMPI_COMM_WORLD_LOCAL_RANK == "0" ]]; then
158
+ rm -rf $OUTPUT_DIR/*/model.ckpt-*
159
+ rm -rf $OUTPUT_DIR/*/checkpoint
160
+ if [[ $USE_DRAM_OUTPUT == "True" ]]; then
161
+ cp -r $LOG_DIR/result_* /root/scratch/bert/bert_gaudi${NUM_WORKERS_TOTAL}_${TESTDATE}_${TESTTIME}
162
+ rm -rf /mnt/dramfs/bert_gaudi${NUM_WORKERS_TOTAL}_${TESTDATE}_${TESTTIME}
163
+ fi
164
+ fi
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/bf16_config/bert.json ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "allowlist": [
3
+ "_ScopedAllocatorSplit",
4
+ "_ScopedAllocatorConcat",
5
+ "_ScopedAllocator",
6
+ "BatchMatMul",
7
+ "BatchMatMulV2",
8
+ "BiasAdd",
9
+ "BiasAddGrad",
10
+ "EuclideanNorm",
11
+ "Exp",
12
+ "HabanaDropout",
13
+ "HabanaDropoutGrad",
14
+ "HabanaDropoutStateful",
15
+ "HabanaGelu",
16
+ "HabanaGeluGrad",
17
+ "HabanaLayerNorm",
18
+ "HabanaLayerNormV2",
19
+ "HabanaLayerNormGrad",
20
+ "HabanaLayerNormGradV2",
21
+ "HabanaMaskedSoftmax",
22
+ "HabanaSoftmaxGrad",
23
+ "HabanaLogSoftmaxGrad",
24
+ "HorovodAllreduce",
25
+ "L2Loss",
26
+ "Log",
27
+ "LogSoftmax",
28
+ "MatMul",
29
+ "Softmax",
30
+ "Sum",
31
+ "Tanh",
32
+ "TanhGrad"
33
+ ],
34
+ "conditional_list": [
35
+ "Add",
36
+ "AddV2",
37
+ "AddN",
38
+ "ExpandDims",
39
+ "Identity",
40
+ "Reshape",
41
+ "Slice",
42
+ "Split",
43
+ "StridedSliceGrad",
44
+ "Transpose"
45
+ ],
46
+ "strict_conditional_list": [],
47
+ "non_convertible_exceptions": [
48
+ [".*KEEP_FP32_PRECISION.*", ""]
49
+ ],
50
+ "convertible_exceptions": [
51
+ ["bert/encoder/layer_[0-9]+/attention/self/add", "AddV2"],
52
+ ["bert/encoder/layer_[0-9]+/attention/self/Mul", "Mul"],
53
+ ["clip_by_global_norm/mul", "Mul"],
54
+ ["global_norm/mul", "Mul"],
55
+ ["global_norm/global_norm", "Sqrt"]
56
+ ]
57
+ }
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/common.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ###############################################################################
2
+ # Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company
3
+ ###############################################################################
4
+
5
+ import os
6
+ import logging
7
+ import subprocess
8
+ import sys
9
+ _log = logging.getLogger(__file__)
10
+
11
+
12
+ def setup_jemalloc() -> None:
13
+ """
14
+ Setup libjemalloc.so.1 or libjemalloc.so.1 (depending on the OS version)
15
+ by exporting LD_PRELOAD env variable.
16
+ """
17
+ _log.info("libjemalloc.so has been requested")
18
+ paths = {"LD_LIBRARY_PATH"}
19
+ env_vals = [os.environ[x] for x in paths if os.environ.get(x) is not None]
20
+ env_vals.extend(["/usr/lib/x86_64-linux-gnu"])
21
+ sep = ":"
22
+ final_path = None
23
+ locations = sep.join(env_vals).split(sep)
24
+ for path in locations:
25
+ if path:
26
+ libpath = f"{path}/libjemalloc.so.1"
27
+ if os.path.isfile(libpath):
28
+ final_path = os.path.realpath(libpath)
29
+ for path in locations:
30
+ if path:
31
+ libpath = f"{path}/libjemalloc.so.2"
32
+ if os.path.isfile(libpath):
33
+ final_path = os.path.realpath(libpath)
34
+ if final_path:
35
+ os.environ["LD_PRELOAD"] = f"{final_path}:{os.environ.get('LD_PRELOAD', '')}"
36
+ else:
37
+ raise FileExistsError("Neither libjemalloc.so.1 nor libjemalloc.so.2 found.")
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/debug.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ ###############################################################################
16
+ # Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company
17
+ ###############################################################################
18
+
19
+ from absl import flags
20
+ from absl import logging
21
+ from tensorflow.core.protobuf import debug_event_pb2
22
+ from tensorflow.python.debug.lib import debug_events_writer
23
+ from tensorflow.python.framework import op_callbacks
24
+ from tensorflow.python.ops import gen_debug_ops
25
+ import tensorflow as tf
26
+ import re
27
+ import os
28
+ import json
29
+
30
+ try:
31
+ import horovod.tensorflow as hvd
32
+ except ImportError:
33
+ hvd = None
34
+
35
+
36
+ flags.DEFINE_string(name='dump_config', default=None,
37
+ help='Defines config for tensor dumping')
38
+
39
+
40
+ class _DumpCallback(object):
41
+ def __init__(self, dump_root, tensor_debug_mode, circular_buffer_size, op_regex, output_regex=None):
42
+ self._dump_root = dump_root
43
+ if hvd is not None and hvd.is_initialized():
44
+ self._dump_root = os.path.join(
45
+ self._dump_root, f"rank_{hvd.rank()}")
46
+ self._tensor_debug_mode = debug_event_pb2.TensorDebugMode.Value(
47
+ tensor_debug_mode)
48
+ self._circular_buffer_size = circular_buffer_size
49
+ self._op_regex = re.compile(op_regex) if isinstance(
50
+ op_regex, str) else op_regex
51
+ self._output_regex = re.compile(output_regex) if isinstance(
52
+ output_regex, str) else output_regex
53
+ self._tfdbg_run_id = ''
54
+ self._dump_op_counter = 0
55
+
56
+ debug_writer_args = {
57
+ "dump_root": self._dump_root,
58
+ "circular_buffer_size": self._circular_buffer_size
59
+ }
60
+
61
+ if not tf.__version__.startswith("2.2"):
62
+ debug_writer_args["tfdbg_run_id"] = self._tfdbg_run_id
63
+
64
+ self._writer = debug_events_writer.DebugEventsWriter(
65
+ **debug_writer_args)
66
+
67
+ def callback(self, op_type, inputs, attrs, outputs, op_name=None, graph=None):
68
+ if op_name is not None and self._op_regex.match(op_name):
69
+ graph_name = "missing-graph-name"
70
+ if graph is not None and hasattr(graph, "name"):
71
+ graph_name = graph.name
72
+
73
+ logging.info("Adding dump op for '%s' of type '%s' from graph '%s'" % (
74
+ op_name, op_type, graph_name))
75
+
76
+ new_outputs = []
77
+
78
+ for output_slot, output in enumerate(outputs):
79
+ if self._output_regex is not None and not self._output_regex.match(output.name):
80
+ logging.info("Skipped output: " + output.name)
81
+ new_outputs.append(output)
82
+ continue
83
+ debug_identity_op_kwargs = {
84
+ "tfdbg_context_id": graph_name,
85
+ "op_name": op_name,
86
+ "output_slot": output_slot,
87
+ "tensor_debug_mode": self._tensor_debug_mode,
88
+ "debug_urls": ["file://%s" % self._dump_root],
89
+ "name": "dump_%d" % self._dump_op_counter
90
+ }
91
+
92
+ if not tf.__version__.startswith("2.2"):
93
+ debug_identity_op_kwargs["circular_buffer_size"] = self._circular_buffer_size
94
+ debug_identity_op_kwargs["tfdbg_run_id"] = self._tfdbg_run_id
95
+
96
+ self._dump_op_counter = self._dump_op_counter + 1
97
+ new_outputs.append(gen_debug_ops.debug_identity_v2(
98
+ output, **debug_identity_op_kwargs))
99
+
100
+ return new_outputs
101
+ else:
102
+ return None
103
+
104
+ def __enter__(self, *args, **kwargs):
105
+ op_callbacks.add_op_callback(self.callback)
106
+ logging.info("Enabled tensor dumping")
107
+
108
+ def __exit__(self, *args, **kwargs):
109
+ op_callbacks.remove_op_callback(self.callback)
110
+ logging.info("Disabled tensor dumping")
111
+
112
+ def __del__(self):
113
+ self._writer.Close()
114
+
115
+
116
+ class _Dummy(object):
117
+ def __enter__(self, *args, **kwargs):
118
+ pass
119
+
120
+ def __exit__(self, *args, **kwargs):
121
+ pass
122
+
123
+
124
+ def dump_callback(config_file=None):
125
+ if config_file is not None:
126
+ kwargs = json.load(open(config_file, 'r'))
127
+ return _DumpCallback(**kwargs)
128
+ try:
129
+ kwargs = json.load(open(flags.FLAGS.dump_config, 'r'))
130
+ return _DumpCallback(**kwargs)
131
+ except:
132
+ return _Dummy()
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/horovod_helpers_gpu.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import horovod.tensorflow as hvd
3
+
4
+ def hvd_init():
5
+ hvd.init()
6
+
7
+ def hvd_size():
8
+ return hvd.size()
9
+
10
+ def hvd_rank():
11
+ return hvd.rank()
12
+
13
+ def comm_size():
14
+ return int(os.environ.get("OMPI_COMM_WORLD_SIZE", 1))
15
+
16
+ def horovod_enabled():
17
+ try:
18
+ return hvd.size() > 1
19
+ except ValueError:
20
+ return False
21
+
22
+ def comm_local_rank():
23
+ return int(os.environ.get("OMPI_COMM_WORLD_LOCAL_RANK", 0))
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/modeling/performance.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Lint as: python3
2
+ # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ # ==============================================================================
16
+ """Functions and classes related to training performance."""
17
+
18
+ import tensorflow as tf
19
+
20
+
21
+ def configure_optimizer(optimizer,
22
+ use_float16=False,
23
+ use_graph_rewrite=False,
24
+ loss_scale="dynamic"):
25
+ """Configures optimizer object with performance options."""
26
+ if use_float16:
27
+ # Wraps optimizer with a LossScaleOptimizer. This is done automatically
28
+ # in compile() with the "mixed_float16" policy, but since we do not call
29
+ # compile(), we must wrap the optimizer manually.
30
+ optimizer = (
31
+ tf.keras.mixed_precision.experimental.LossScaleOptimizer(
32
+ optimizer, loss_scale=loss_scale))
33
+ if use_graph_rewrite:
34
+ # Note: the model dtype must be 'float32', which will ensure
35
+ # tf.ckeras.mixed_precision and
36
+ # tf.train.experimental.enable_mixed_precision_graph_rewrite do not double
37
+ # up.
38
+ optimizer = tf.train.experimental.enable_mixed_precision_graph_rewrite(
39
+ optimizer)
40
+ return optimizer
41
+
42
+
43
+ def set_mixed_precision_policy(dtype, loss_scale=None):
44
+ """Sets mix precision policy."""
45
+ if dtype == tf.float16:
46
+ policy = tf.keras.mixed_precision.experimental.Policy(
47
+ 'mixed_float16', loss_scale=loss_scale)
48
+ tf.keras.mixed_precision.experimental.set_policy(policy)
49
+ elif dtype == tf.bfloat16:
50
+ policy = tf.keras.mixed_precision.experimental.Policy(
51
+ 'mixed_bfloat16')
52
+ tf.keras.mixed_precision.experimental.set_policy(policy)
53
+ elif dtype == tf.float32:
54
+ tf.keras.mixed_precision.experimental.set_policy('float32')
55
+ else:
56
+ raise ValueError("Unexpected dtype: %s" % dtype)
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/modeling/tf_utils.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """Common TF utilities."""
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ from __future__ import print_function
20
+
21
+ import six
22
+ import tensorflow as tf
23
+
24
+ from tensorflow.python.util import deprecation
25
+ from TensorFlow.common.modeling import activations
26
+
27
+
28
+ @deprecation.deprecated(
29
+ None,
30
+ "tf.keras.layers.Layer supports multiple positional args and kwargs as "
31
+ "input tensors. pack/unpack inputs to override __call__ is no longer "
32
+ "needed."
33
+ )
34
+ def pack_inputs(inputs):
35
+ """Pack a list of `inputs` tensors to a tuple.
36
+
37
+ Args:
38
+ inputs: a list of tensors.
39
+
40
+ Returns:
41
+ a tuple of tensors. if any input is None, replace it with a special constant
42
+ tensor.
43
+ """
44
+ inputs = tf.nest.flatten(inputs)
45
+ outputs = []
46
+ for x in inputs:
47
+ if x is None:
48
+ outputs.append(tf.constant(0, shape=[], dtype=tf.int32))
49
+ else:
50
+ outputs.append(x)
51
+ return tuple(outputs)
52
+
53
+
54
+ @deprecation.deprecated(
55
+ None,
56
+ "tf.keras.layers.Layer supports multiple positional args and kwargs as "
57
+ "input tensors. pack/unpack inputs to override __call__ is no longer "
58
+ "needed."
59
+ )
60
+ def unpack_inputs(inputs):
61
+ """unpack a tuple of `inputs` tensors to a tuple.
62
+
63
+ Args:
64
+ inputs: a list of tensors.
65
+
66
+ Returns:
67
+ a tuple of tensors. if any input is a special constant tensor, replace it
68
+ with None.
69
+ """
70
+ inputs = tf.nest.flatten(inputs)
71
+ outputs = []
72
+ for x in inputs:
73
+ if is_special_none_tensor(x):
74
+ outputs.append(None)
75
+ else:
76
+ outputs.append(x)
77
+ x = tuple(outputs)
78
+
79
+ # To trick the very pointless 'unbalanced-tuple-unpacking' pylint check
80
+ # from triggering.
81
+ if len(x) == 1:
82
+ return x[0]
83
+ return tuple(outputs)
84
+
85
+
86
+ def is_special_none_tensor(tensor):
87
+ """Checks if a tensor is a special None Tensor."""
88
+ return tensor.shape.ndims == 0 and tensor.dtype == tf.int32
89
+
90
+
91
+ # TODO(hongkuny): consider moving custom string-map lookup to keras api.
92
+ def get_activation(identifier):
93
+ """Maps a identifier to a Python function, e.g., "relu" => `tf.nn.relu`.
94
+
95
+ It checks string first and if it is one of customized activation not in TF,
96
+ the corresponding activation will be returned. For non-customized activation
97
+ names and callable identifiers, always fallback to tf.keras.activations.get.
98
+
99
+ Args:
100
+ identifier: String name of the activation function or callable.
101
+
102
+ Returns:
103
+ A Python function corresponding to the activation function.
104
+ """
105
+ if isinstance(identifier, six.string_types):
106
+ name_to_fn = {
107
+ "gelu": activations.gelu,
108
+ "simple_swish": activations.simple_swish,
109
+ "hard_swish": activations.hard_swish,
110
+ "identity": activations.identity,
111
+ }
112
+ identifier = str(identifier).lower()
113
+ if identifier in name_to_fn:
114
+ return tf.keras.activations.get(name_to_fn[identifier])
115
+ return tf.keras.activations.get(identifier)
116
+
117
+
118
+ def get_shape_list(tensor, expected_rank=None, name=None):
119
+ """Returns a list of the shape of tensor, preferring static dimensions.
120
+
121
+ Args:
122
+ tensor: A tf.Tensor object to find the shape of.
123
+ expected_rank: (optional) int. The expected rank of `tensor`. If this is
124
+ specified and the `tensor` has a different rank, and exception will be
125
+ thrown.
126
+ name: Optional name of the tensor for the error message.
127
+
128
+ Returns:
129
+ A list of dimensions of the shape of tensor. All static dimensions will
130
+ be returned as python integers, and dynamic dimensions will be returned
131
+ as tf.Tensor scalars.
132
+ """
133
+ if expected_rank is not None:
134
+ assert_rank(tensor, expected_rank, name)
135
+
136
+ shape = tensor.shape.as_list()
137
+
138
+ non_static_indexes = []
139
+ for (index, dim) in enumerate(shape):
140
+ if dim is None:
141
+ non_static_indexes.append(index)
142
+
143
+ if not non_static_indexes:
144
+ return shape
145
+
146
+ dyn_shape = tf.shape(tensor)
147
+ for index in non_static_indexes:
148
+ shape[index] = dyn_shape[index]
149
+ return shape
150
+
151
+
152
+ def assert_rank(tensor, expected_rank, name=None):
153
+ """Raises an exception if the tensor rank is not of the expected rank.
154
+
155
+ Args:
156
+ tensor: A tf.Tensor to check the rank of.
157
+ expected_rank: Python integer or list of integers, expected rank.
158
+ name: Optional name of the tensor for the error message.
159
+
160
+ Raises:
161
+ ValueError: If the expected shape doesn't match the actual shape.
162
+ """
163
+ expected_rank_dict = {}
164
+ if isinstance(expected_rank, six.integer_types):
165
+ expected_rank_dict[expected_rank] = True
166
+ else:
167
+ for x in expected_rank:
168
+ expected_rank_dict[x] = True
169
+
170
+ actual_rank = tensor.shape.ndims
171
+ if actual_rank not in expected_rank_dict:
172
+ raise ValueError(
173
+ "For the tensor `%s`, the actual tensor rank `%d` (shape = %s) is not "
174
+ "equal to the expected tensor rank `%s`" %
175
+ (name, actual_rank, str(tensor.shape), str(expected_rank)))
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/tb_utils.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import tensorflow as tf
4
+ from copy import deepcopy
5
+ from tensorboard.plugins.hparams import api as hp
6
+ from tensorflow.python.eager import context
7
+ from tensorflow.keras import backend as K
8
+ from tensorflow.python.ops import summary_ops_v2
9
+ from tensorflow.python.summary import summary as tf_summary
10
+ from tensorflow.python.training.summary_io import SummaryWriterCache
11
+ from tensorflow.compat.v1.keras.callbacks import TensorBoard, Callback
12
+
13
+
14
+ def _remove_prefix(s, prefix):
15
+ if s.startswith(prefix):
16
+ s = s[len(prefix):]
17
+ return s
18
+
19
+
20
+ def _parse_precision():
21
+ flag = os.environ.get('TF_BF16_CONVERSION', '0')
22
+ flag = flag.lower()
23
+ try:
24
+ value = int(flag)
25
+ except:
26
+ value = -1
27
+
28
+ if flag == 'false' or value == 0:
29
+ return 'fp32'
30
+ elif flag == 'true' or value == 1:
31
+ return 'bf16'
32
+ return flag
33
+
34
+
35
+ def _set_precision_if_missing(hparams: dict):
36
+ if 'precision' not in hparams:
37
+ hparams['precision'] = _parse_precision()
38
+ return hparams
39
+
40
+
41
+ def _copy_and_clean_hparams(hparams: dict):
42
+ hparams_ = dict()
43
+ for name, value in hparams.items():
44
+ if isinstance(value, (str, bool, int, float)):
45
+ hparams_[name] = value
46
+ continue
47
+
48
+ try:
49
+ hparams_[name] = str(value)
50
+ tf.compat.v1.logging.info(
51
+ f'Type of parameter "{name}" is not one of (bool, int, float, str). '
52
+ 'It will be saved as a string.')
53
+ except:
54
+ tf.compat.v1.logging.info(
55
+ f'Conversion of parameter "{name}" to string failed. '
56
+ 'Parameter will not be saved.')
57
+
58
+ return hparams_
59
+
60
+
61
+ def write_hparams_v1(writer, hparams: dict):
62
+ hparams = _copy_and_clean_hparams(hparams)
63
+ hparams = _set_precision_if_missing(hparams)
64
+
65
+ # We create Session here, because in case of older topologies
66
+ # that run in graph mode the FileWriter needs it.
67
+ with tf.compat.v1.Session():
68
+ if isinstance(writer, str):
69
+ writer = SummaryWriterCache.get(writer)
70
+ summary = hp.hparams_pb(hparams).SerializeToString()
71
+ writer.add_summary(summary)
72
+
73
+
74
+ def write_hparams_v2(writer, hparams: dict):
75
+ hparams = _copy_and_clean_hparams(hparams)
76
+ hparams = _set_precision_if_missing(hparams)
77
+
78
+ with writer.as_default():
79
+ hp.hparams(hparams)
80
+
81
+
82
+ class ExamplesPerSecondEstimatorHook(tf.compat.v1.train.StepCounterHook):
83
+ """Calculate and report global_step/sec and examples/sec during runtime."""
84
+ # Copy-pasted from tensorflow_estimator/python/estimator/tpu/tpu_estimator.py
85
+
86
+ def __init__(self,
87
+ batch_size=None,
88
+ every_n_steps=1,
89
+ every_n_secs=None,
90
+ output_dir=None,
91
+ summary_writer=None,
92
+ extra_metrics=None,
93
+ verbose=False):
94
+ super().__init__(
95
+ every_n_steps=every_n_steps,
96
+ every_n_secs=every_n_secs,
97
+ output_dir=output_dir,
98
+ summary_writer=summary_writer)
99
+ self._extra_metrics = extra_metrics or {}
100
+ self._verbose = verbose
101
+ if batch_size is not None:
102
+ self._extra_metrics['examples/sec'] = batch_size
103
+
104
+ def _add_summary(self, tag, value, step):
105
+ Summary = tf.compat.v1.Summary
106
+ global_step_summary = Summary(value=[
107
+ Summary.Value(tag=tag, simple_value=value)
108
+ ])
109
+ self._summary_writer.add_summary(global_step_summary, step)
110
+ if self._verbose:
111
+ tf.compat.v1.logging.info(f'{tag}: {value}')
112
+
113
+ def _log_and_record(self, elapsed_steps, elapsed_time, global_step):
114
+ global_step_per_sec = elapsed_steps / elapsed_time
115
+ if self._summary_writer is not None:
116
+ self._add_summary('global_step/sec',
117
+ global_step_per_sec, global_step)
118
+ for name, factor in self._extra_metrics.items():
119
+ value = factor * global_step_per_sec
120
+ self._add_summary(name, value, global_step)
121
+
122
+
123
+ class ExamplesPerSecondKerasHook(Callback):
124
+ def __init__(self,
125
+ every_n_steps=1,
126
+ every_n_secs=None,
127
+ output_dir=None,
128
+ summary_writer=None):
129
+ self.writer = summary_writer or SummaryWriterCache.get(output_dir)
130
+ self._timer = tf.compat.v1.train.SecondOrStepTimer(
131
+ every_n_secs, every_n_steps)
132
+ self._total_examples = 0
133
+ self._should_trigger = True
134
+
135
+ def on_train_begin(self, logs=None):
136
+ self._timer.reset()
137
+
138
+ def on_train_batch_begin(self, batch, logs=None):
139
+ self._should_trigger = self._timer.should_trigger_for_step(
140
+ logs.get('batch', 0))
141
+
142
+ def on_train_batch_end(self, batch, logs=None):
143
+ step = logs.get('batch', 0)
144
+ self._total_examples += logs.get('size', 0)
145
+ if self._should_trigger:
146
+ elapsed_time, elapsed_steps = self._timer.update_last_triggered_step(
147
+ step)
148
+ if elapsed_time is not None:
149
+ self._log_and_record(
150
+ elapsed_steps, elapsed_time, step, self._total_examples)
151
+ self._total_examples = 0
152
+
153
+ def _log_and_record(self, elapsed_steps, elapsed_time,
154
+ global_step, total_examples=None):
155
+ Summary = tf.compat.v1.Summary
156
+ global_step_per_sec = elapsed_steps / elapsed_time
157
+ if self.writer is not None:
158
+ global_step_summary = Summary(value=[
159
+ Summary.Value(
160
+ tag='global_step/sec', simple_value=global_step_per_sec)
161
+ ])
162
+ self.writer.add_summary(global_step_summary, global_step)
163
+ if total_examples is not None:
164
+ examples_per_sec = total_examples / elapsed_time
165
+ example_summary = Summary(value=[
166
+ Summary.Value(tag='examples/sec',
167
+ simple_value=examples_per_sec)
168
+ ])
169
+ self.writer.add_summary(example_summary, global_step)
170
+
171
+
172
+ class TBSummary(object):
173
+ """
174
+ Creates a proxy for FileWriter for TensorBoard.
175
+
176
+ :param log_dir: - path where experiment is running (usually the same as
177
+ model_dir in Estimator)
178
+ """
179
+
180
+ def __init__(self, log_dir: str):
181
+ super().__init__()
182
+ self._log_dir = log_dir
183
+ self._session = None
184
+
185
+ def __enter__(self):
186
+ self._session = tf.compat.v1.Session()
187
+ return self
188
+
189
+ def __exit__(self, exc_type, exc_val, exc_tb):
190
+ if self._session:
191
+ self._session.close()
192
+ self._session = None
193
+
194
+ def add_scalar(self, tag, value, global_step=None):
195
+ with self._session:
196
+ writer = SummaryWriterCache.get(self._log_dir)
197
+ summary = tf.compat.v1.Summary(
198
+ value=[tf.compat.v1.Summary.Value(tag=tag, simple_value=value)])
199
+ event = tf.compat.v1.Event(summary=summary)
200
+ event.wall_time = time.time()
201
+ event.step = global_step
202
+ writer.add_event(event)
203
+
204
+
205
+ class TensorBoardWithHParamsV1(TensorBoard):
206
+ """
207
+ Adds TensorBoard visualization to training process.
208
+
209
+ Writes training tfevent file into default log directory, but
210
+ stores evaluation in log_dir/eval subdirectory.
211
+ """
212
+
213
+ def __init__(self, hparams, *args, **kwargs):
214
+ super().__init__(*args, **kwargs)
215
+ self.hparams = hparams
216
+ self._train_writer = None
217
+ self._eval_writer = None
218
+
219
+ def _switch_writer(self, mode):
220
+ self.writer = self._train_writer if mode == 'train' else self._eval_writer
221
+
222
+ def _init_writer(self, model):
223
+ """Sets file writer."""
224
+ if context.executing_eagerly():
225
+ raise NotImplementedError('hook does not support eager execution')
226
+
227
+ self._train_writer = SummaryWriterCache.get(self.log_dir)
228
+ self._eval_writer = SummaryWriterCache.get(
229
+ os.path.join(self.log_dir, 'eval'))
230
+ self._switch_writer('train')
231
+
232
+ write_hparams_v1(self.writer, self.hparams)
233
+
234
+ def _write_custom_summaries(self, step, logs=None):
235
+ """
236
+ This methods works on the assumption that metrics containing `val`
237
+ in name are related to validation (that's the default in Keras).
238
+ """
239
+
240
+ logs = logs or {}
241
+ train_logs = {}
242
+ eval_logs = {}
243
+
244
+ for name, value in logs.items():
245
+ if 'val' in name:
246
+ if name.startswith('batch_val_'):
247
+ name = 'batch_' + _remove_prefix(name, 'batch_val_')
248
+ elif name.startswith('epoch_val_'):
249
+ name = _remove_prefix(name, 'epoch_val_')
250
+ eval_logs[name] = value
251
+ else:
252
+ if name.startswith('batch_'):
253
+ name = _remove_prefix(name, 'batch_')
254
+ train_logs[name] = value
255
+
256
+ self._switch_writer('eval')
257
+ super()._write_custom_summaries(step, eval_logs)
258
+ self._switch_writer('train')
259
+ super()._write_custom_summaries(step, train_logs)
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/common/utils.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ******************************************************************************
2
+ # Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company
3
+ # ******************************************************************************
4
+
5
+ import logging
6
+ import os
7
+ import sys
8
+ from contextlib import contextmanager
9
+ from tensorflow.python.training.session_run_hook import SessionRunHook, SessionRunArgs
10
+
11
+ import tensorflow as tf
12
+ from tensorflow.python.training import training_util
13
+ from tensorflow.core.protobuf import config_pb2
14
+ from tensorflow.python.client import timeline
15
+ from tensorflow.python.platform import gfile
16
+
17
+ @contextmanager
18
+ def disable_session_recovery():
19
+ """ Disable session recovery on backend errors.
20
+
21
+ MonitoredSession that is used by Estimator hard-codes that AbortedError
22
+ and UnavailableError should not terminate but instead silently restart
23
+ training. This constitutes a broad list of c++ backend errors, including
24
+ OOM, that may cause endless error/restart loop.
25
+ """
26
+ from tensorflow.python.training import training
27
+ module= sys.modules['tensorflow.python.training.monitored_session']
28
+ ignored_error_list_attr = "_PREEMPTION_ERRORS"
29
+ orig_ignored_errors = getattr(module, ignored_error_list_attr)
30
+ setattr(module, ignored_error_list_attr, tuple())
31
+ yield
32
+ setattr(module, ignored_error_list_attr, orig_ignored_errors)
33
+
34
+
35
+ class RangeTFChromeProfilerHook(tf.compat.v1.estimator.SessionRunHook):
36
+
37
+ def __init__(self,
38
+ start_iter=None,
39
+ num_iters=None,
40
+ output_dir="."):
41
+ self._start_iter=start_iter
42
+ self._end_iter=start_iter+num_iters
43
+ self._curr_iter=0
44
+ self._output_dir=output_dir
45
+ self._metadata=[]
46
+
47
+ def before_run(self, run_context):
48
+ self._curr_iter=self._curr_iter+1
49
+ if self._curr_iter > self._start_iter and self._curr_iter <= self._end_iter:
50
+ return tf.estimator.SessionRunArgs(None, options=config_pb2.RunOptions(trace_level=config_pb2.RunOptions.FULL_TRACE))
51
+ else:
52
+ return None
53
+
54
+ def after_run(self, run_context, run_values):
55
+ if self._curr_iter > self._start_iter and self._curr_iter <= self._end_iter:
56
+ self._metadata.append(run_values.run_metadata.step_stats)
57
+
58
+ if self._curr_iter == self._end_iter:
59
+ self._save(self._curr_iter, self._output_dir)
60
+ run_context.request_stop()
61
+
62
+ def _save(self, step, save_path):
63
+ logging.info("Saving timeline for %d into '%s'.", step, save_path)
64
+ if not os.path.exists(save_path):
65
+ os.makedirs(save_path)
66
+
67
+ traces=self._metadata[0]
68
+ for ds in self._metadata[1:]:
69
+ traces.dev_stats.MergeFrom(ds.dev_stats)
70
+
71
+ with gfile.Open("{}/tf_trace.json".format(save_path), "w") as f:
72
+ trace = timeline.Timeline(traces)
73
+ f.write(
74
+ trace.generate_chrome_trace_format(show_dataflow=False, show_memory=False))
75
+
76
+
77
+ class RangeTFHltvProfilerHook(SessionRunHook):
78
+ def __init__(self,
79
+ output_dir="",
80
+ profile_steps=""
81
+ ):
82
+ self.output_dir = output_dir
83
+ profile_steps_error_message = (
84
+ 'profile_steps must be a comma separated pair of positive integers, '
85
+ 'specifying the first and last steps to be profiled.'
86
+ )
87
+ try:
88
+ profile_steps = [int(i) for i in profile_steps.split(',')]
89
+ except ValueError:
90
+ raise ValueError(profile_steps_error_message)
91
+ if len(profile_steps) != 2:
92
+ raise ValueError(profile_steps_error_message)
93
+ self.start_step, self.stop_step = profile_steps
94
+ if self.start_step < 0 or self.start_step > self.stop_step:
95
+ raise ValueError(profile_steps_error_message)
96
+ self._step=0
97
+
98
+ def before_run(self, run_context):
99
+ if self._step == self.start_step:
100
+ tf.profiler.experimental.start(self.output_dir)
101
+ elif self._step == self.stop_step+1:
102
+ tf.profiler.experimental.stop()
103
+
104
+ self._step = self._step + 1
105
+ return SessionRunArgs({})
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/README.md ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adding Abseil (absl) flags quickstart
2
+ ## Defining a flag
3
+ absl flag definitions are similar to argparse, although they are defined on a global namespace.
4
+
5
+ For instance defining a string flag looks like:
6
+ ```$xslt
7
+ from absl import flags
8
+ flags.DEFINE_string(
9
+ name="my_flag",
10
+ default="a_sensible_default",
11
+ help="Here is what this flag does."
12
+ )
13
+ ```
14
+
15
+ All three arguments are required, but default may be `None`. A common optional argument is
16
+ short_name for defining abreviations. Certain `DEFINE_*` methods will have other required arguments.
17
+ For instance `DEFINE_enum` requires the `enum_values` argument to be specified.
18
+
19
+ ## Key Flags
20
+ absl has the concept of a key flag. Any flag defined in `__main__` is considered a key flag by
21
+ default. Key flags are displayed in `--help`, others only appear in `--helpfull`. In order to
22
+ handle key flags that are defined outside the module in question, absl provides the
23
+ `flags.adopt_module_key_flags()` method. This adds the key flags of a different module to one's own
24
+ key flags. For example:
25
+ ```$xslt
26
+ File: flag_source.py
27
+ ---------------------------------------
28
+
29
+ from absl import flags
30
+ flags.DEFINE_string(name="my_flag", default="abc", help="a flag.")
31
+ ```
32
+
33
+ ```$xslt
34
+ File: my_module.py
35
+ ---------------------------------------
36
+
37
+ from absl import app as absl_app
38
+ from absl import flags
39
+
40
+ import flag_source
41
+
42
+ flags.adopt_module_key_flags(flag_source)
43
+
44
+ def main(_):
45
+ pass
46
+
47
+ absl_app.run(main, [__file__, "-h"]
48
+ ```
49
+
50
+ when `my_module.py` is run it will show the help text for `my_flag`. Because not all flags defined
51
+ in a file are equally important, `official/utils/flags/core.py` (generally imported as flags_core)
52
+ provides an abstraction for handling key flag declaration in an easy way through the
53
+ `register_key_flags_in_core()` function, which allows a module to make a single
54
+ `adopt_key_flags(flags_core)` call when using the util flag declaration functions.
55
+
56
+ ## Validators
57
+ Often the constraints on a flag are complicated. absl provides the validator decorator to allow
58
+ one to mark a function as a flag validation function. Suppose we want users to provide a flag
59
+ which is a palindrome.
60
+
61
+ ```$xslt
62
+ from absl import flags
63
+
64
+ flags.DEFINE_string(name="pal_flag", short_name="pf", default="", help="Give me a palindrome")
65
+
66
+ @flags.validator("pal_flag")
67
+ def _check_pal(provided_pal_flag):
68
+ return provided_pal_flag == provided_pal_flag[::-1]
69
+
70
+ ```
71
+
72
+ Validators take the form that returning True (truthy) passes, and all others
73
+ (False, None, exception) fail.
74
+
75
+ ## Testing
76
+ To test using absl, simply declare flags in the setupClass method of TensorFlow's TestCase.
77
+
78
+ ```$xslt
79
+ from absl import flags
80
+ import tensorflow as tf
81
+
82
+ def define_flags():
83
+ flags.DEFINE_string(name="test_flag", default="abc", help="an example flag")
84
+
85
+
86
+ class BaseTester(unittest.TestCase):
87
+
88
+ @classmethod
89
+ def setUpClass(cls):
90
+ super(BaseTester, cls).setUpClass()
91
+ define_flags()
92
+
93
+ def test_trivial(self):
94
+ flags_core.parse_flags([__file__, "test_flag", "def"])
95
+ self.AssertEqual(flags.FLAGS.test_flag, "def")
96
+
97
+ ```
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/__init__.py ADDED
File without changes
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/_base.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """Flags which will be nearly universal across models."""
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ from __future__ import print_function
20
+
21
+ from absl import flags
22
+ import tensorflow as tf
23
+
24
+ from TensorFlow.utils.flags._conventions import help_wrap
25
+ from TensorFlow.utils.logs import hooks_helper
26
+
27
+
28
+ def define_base(data_dir=True, model_dir=True, clean=False, train_epochs=False,
29
+ epochs_between_evals=False, stop_threshold=False,
30
+ batch_size=True, num_gpu=False, hooks=False, export_dir=False,
31
+ distribution_strategy=False, run_eagerly=False):
32
+ """Register base flags.
33
+
34
+ Args:
35
+ data_dir: Create a flag for specifying the input data directory.
36
+ model_dir: Create a flag for specifying the model file directory.
37
+ clean: Create a flag for removing the model_dir.
38
+ train_epochs: Create a flag to specify the number of training epochs.
39
+ epochs_between_evals: Create a flag to specify the frequency of testing.
40
+ stop_threshold: Create a flag to specify a threshold accuracy or other
41
+ eval metric which should trigger the end of training.
42
+ batch_size: Create a flag to specify the batch size.
43
+ num_gpu: Create a flag to specify the number of GPUs used.
44
+ hooks: Create a flag to specify hooks for logging.
45
+ export_dir: Create a flag to specify where a SavedModel should be exported.
46
+ distribution_strategy: Create a flag to specify which Distribution Strategy
47
+ to use.
48
+ run_eagerly: Create a flag to specify to run eagerly op by op.
49
+ Returns:
50
+ A list of flags for core.py to marks as key flags.
51
+ """
52
+ key_flags = []
53
+
54
+ if data_dir:
55
+ flags.DEFINE_string(
56
+ name="data_dir", short_name="dd", default="/tmp",
57
+ help=help_wrap("The location of the input data."))
58
+ key_flags.append("data_dir")
59
+
60
+ if model_dir:
61
+ flags.DEFINE_string(
62
+ name="model_dir", short_name="md", default="/tmp",
63
+ help=help_wrap("The location of the model checkpoint files."))
64
+ key_flags.append("model_dir")
65
+
66
+ if clean:
67
+ flags.DEFINE_boolean(
68
+ name="clean", default=False,
69
+ help=help_wrap("If set, model_dir will be removed if it exists."))
70
+ key_flags.append("clean")
71
+
72
+ if train_epochs:
73
+ flags.DEFINE_integer(
74
+ name="train_epochs", short_name="te", default=1,
75
+ help=help_wrap("The number of epochs used to train."))
76
+ key_flags.append("train_epochs")
77
+
78
+ if epochs_between_evals:
79
+ flags.DEFINE_integer(
80
+ name="epochs_between_evals", short_name="ebe", default=1,
81
+ help=help_wrap("The number of training epochs to run between "
82
+ "evaluations."))
83
+ key_flags.append("epochs_between_evals")
84
+
85
+ if stop_threshold:
86
+ flags.DEFINE_float(
87
+ name="stop_threshold", short_name="st",
88
+ default=None,
89
+ help=help_wrap("If passed, training will stop at the earlier of "
90
+ "train_epochs and when the evaluation metric is "
91
+ "greater than or equal to stop_threshold."))
92
+
93
+ if batch_size:
94
+ flags.DEFINE_integer(
95
+ name="batch_size", short_name="bs", default=32,
96
+ help=help_wrap("Batch size for training and evaluation. When using "
97
+ "multiple gpus, this is the global batch size for "
98
+ "all devices. For example, if the batch size is 32 "
99
+ "and there are 4 GPUs, each GPU will get 8 examples on "
100
+ "each step."))
101
+ key_flags.append("batch_size")
102
+
103
+ if num_gpu:
104
+ flags.DEFINE_integer(
105
+ name="num_gpus", short_name="ng",
106
+ default=1,
107
+ help=help_wrap(
108
+ "How many GPUs to use at each worker with the "
109
+ "DistributionStrategies API. The default is 1."))
110
+
111
+ if run_eagerly:
112
+ flags.DEFINE_boolean(
113
+ name="run_eagerly", default=False,
114
+ help="Run the model op by op without building a model function.")
115
+
116
+ if hooks:
117
+ # Construct a pretty summary of hooks.
118
+ hook_list_str = (
119
+ u"\ufeff Hook:\n" + u"\n".join([u"\ufeff {}".format(key) for key
120
+ in hooks_helper.HOOKS]))
121
+ flags.DEFINE_list(
122
+ name="hooks", short_name="hk", default="LoggingTensorHook",
123
+ help=help_wrap(
124
+ u"A list of (case insensitive) strings to specify the names of "
125
+ u"training hooks.\n{}\n\ufeff Example: `--hooks ProfilerHook,"
126
+ u"ExamplesPerSecondHook`\n See official.utils.logs.hooks_helper "
127
+ u"for details.".format(hook_list_str))
128
+ )
129
+ key_flags.append("hooks")
130
+
131
+ if export_dir:
132
+ flags.DEFINE_string(
133
+ name="export_dir", short_name="ed", default=None,
134
+ help=help_wrap("If set, a SavedModel serialization of the model will "
135
+ "be exported to this directory at the end of training. "
136
+ "See the README for more details and relevant links.")
137
+ )
138
+ key_flags.append("export_dir")
139
+
140
+ if distribution_strategy:
141
+ flags.DEFINE_string(
142
+ name="distribution_strategy", short_name="ds", default="mirrored",
143
+ help=help_wrap("The Distribution Strategy to use for training. "
144
+ "Accepted values are 'off', 'one_device', "
145
+ "'mirrored', 'parameter_server', 'collective', "
146
+ "case insensitive. 'off' means not to use "
147
+ "Distribution Strategy; 'default' means to choose "
148
+ "from `MirroredStrategy` or `OneDeviceStrategy` "
149
+ "according to the number of GPUs.")
150
+ )
151
+
152
+
153
+ return key_flags
154
+
155
+
156
+ def get_num_gpus(flags_obj):
157
+ """Treat num_gpus=-1 as 'use all'."""
158
+ if flags_obj.num_gpus != -1:
159
+ return flags_obj.num_gpus
160
+
161
+ from tensorflow.python.client import device_lib # pylint: disable=g-import-not-at-top
162
+ local_device_protos = device_lib.list_local_devices()
163
+ return sum([1 for d in local_device_protos if d.device_type == "GPU"])
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/_conventions.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """Central location for shared argparse convention definitions."""
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ from __future__ import print_function
20
+
21
+ import sys
22
+ import codecs
23
+ import functools
24
+
25
+ from absl import app as absl_app
26
+ from absl import flags
27
+
28
+
29
+ # This codifies help string conventions and makes it easy to update them if
30
+ # necessary. Currently the only major effect is that help bodies start on the
31
+ # line after flags are listed. All flag definitions should wrap the text bodies
32
+ # with help wrap when calling DEFINE_*.
33
+ _help_wrap = functools.partial(flags.text_wrap, length=80, indent="",
34
+ firstline_indent="\n")
35
+
36
+
37
+ # Pretty formatting causes issues when utf-8 is not installed on a system.
38
+ def _stdout_utf8():
39
+ try:
40
+ codecs.lookup("utf-8")
41
+ except LookupError:
42
+ return False
43
+ return sys.stdout.encoding == "UTF-8"
44
+
45
+
46
+ if _stdout_utf8():
47
+ help_wrap = _help_wrap
48
+ else:
49
+ def help_wrap(text, *args, **kwargs):
50
+ return _help_wrap(text, *args, **kwargs).replace(u"\ufeff", u"")
51
+
52
+
53
+ # Replace None with h to also allow -h
54
+ absl_app.HelpshortFlag.SHORT_NAME = "h"
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/_device.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """Flags for managing compute devices. Currently only contains TPU flags."""
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ from __future__ import print_function
20
+
21
+ from absl import flags
22
+ import tensorflow as tf
23
+
24
+ from TensorFlow.utils.flags._conventions import help_wrap
25
+
26
+
27
+ def require_cloud_storage(flag_names):
28
+ """Register a validator to check directory flags.
29
+ Args:
30
+ flag_names: An iterable of strings containing the names of flags to be
31
+ checked.
32
+ """
33
+ msg = "TPU requires GCS path for {}".format(", ".join(flag_names))
34
+ @flags.multi_flags_validator(["tpu"] + flag_names, message=msg)
35
+ def _path_check(flag_values): # pylint: disable=missing-docstring
36
+ if flag_values["tpu"] is None:
37
+ return True
38
+
39
+ valid_flags = True
40
+ for key in flag_names:
41
+ if not flag_values[key].startswith("gs://"):
42
+ tf.compat.v1.logging.error("{} must be a GCS path.".format(key))
43
+ valid_flags = False
44
+
45
+ return valid_flags
46
+
47
+
48
+ def define_device(tpu=True):
49
+ """Register device specific flags.
50
+ Args:
51
+ tpu: Create flags to specify TPU operation.
52
+ Returns:
53
+ A list of flags for core.py to marks as key flags.
54
+ """
55
+
56
+ key_flags = []
57
+
58
+ if tpu:
59
+ flags.DEFINE_string(
60
+ name="tpu", default=None,
61
+ help=help_wrap(
62
+ "The Cloud TPU to use for training. This should be either the name "
63
+ "used when creating the Cloud TPU, or a "
64
+ "grpc://ip.address.of.tpu:8470 url. Passing `local` will use the"
65
+ "CPU of the local instance instead. (Good for debugging.)"))
66
+ key_flags.append("tpu")
67
+
68
+ flags.DEFINE_string(
69
+ name="tpu_zone", default=None,
70
+ help=help_wrap(
71
+ "[Optional] GCE zone where the Cloud TPU is located in. If not "
72
+ "specified, we will attempt to automatically detect the GCE "
73
+ "project from metadata."))
74
+
75
+ flags.DEFINE_string(
76
+ name="tpu_gcp_project", default=None,
77
+ help=help_wrap(
78
+ "[Optional] Project name for the Cloud TPU-enabled project. If not "
79
+ "specified, we will attempt to automatically detect the GCE "
80
+ "project from metadata."))
81
+
82
+ flags.DEFINE_integer(name="num_tpu_shards", default=8,
83
+ help=help_wrap("Number of shards (TPU chips)."))
84
+
85
+ return key_flags
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/core.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """Public interface for flag definition.
16
+
17
+ See _example.py for detailed instructions on defining flags.
18
+ """
19
+
20
+ from __future__ import absolute_import
21
+ from __future__ import division
22
+ from __future__ import print_function
23
+
24
+ import sys
25
+ from six.moves import shlex_quote
26
+
27
+ from absl import app as absl_app
28
+ from absl import flags
29
+
30
+ from TensorFlow.utils.flags import _base
31
+ from TensorFlow.utils.flags import _benchmark
32
+ from TensorFlow.utils.flags import _conventions
33
+ from TensorFlow.utils.flags import _device
34
+ from TensorFlow.utils.flags import _distribution
35
+ from TensorFlow.utils.flags import _misc
36
+ from TensorFlow.utils.flags import _performance
37
+
38
+
39
+ def set_defaults(**kwargs):
40
+ for key, value in kwargs.items():
41
+ flags.FLAGS.set_default(name=key, value=value)
42
+
43
+
44
+ def parse_flags(argv=None):
45
+ """Reset flags and reparse. Currently only used in testing."""
46
+ flags.FLAGS.unparse_flags()
47
+ absl_app.parse_flags_with_usage(argv or sys.argv)
48
+
49
+
50
+ def register_key_flags_in_core(f):
51
+ """Defines a function in core.py, and registers its key flags.
52
+
53
+ absl uses the location of a flags.declare_key_flag() to determine the context
54
+ in which a flag is key. By making all declares in core, this allows model
55
+ main functions to call flags.adopt_module_key_flags() on core and correctly
56
+ chain key flags.
57
+
58
+ Args:
59
+ f: The function to be wrapped
60
+
61
+ Returns:
62
+ The "core-defined" version of the input function.
63
+ """
64
+
65
+ def core_fn(*args, **kwargs):
66
+ key_flags = f(*args, **kwargs)
67
+ [flags.declare_key_flag(fl) for fl in key_flags] # pylint: disable=expression-not-assigned
68
+ return core_fn
69
+
70
+
71
+ define_base = register_key_flags_in_core(_base.define_base)
72
+ # We have define_base_eager for compatibility, since it used to be a separate
73
+ # function from define_base.
74
+ define_base_eager = define_base
75
+ define_log_steps = register_key_flags_in_core(_benchmark.define_log_steps)
76
+ define_benchmark = register_key_flags_in_core(_benchmark.define_benchmark)
77
+ define_device = register_key_flags_in_core(_device.define_device)
78
+ define_image = register_key_flags_in_core(_misc.define_image)
79
+ define_performance = register_key_flags_in_core(_performance.define_performance)
80
+ define_distribution = register_key_flags_in_core(
81
+ _distribution.define_distribution)
82
+
83
+
84
+ help_wrap = _conventions.help_wrap
85
+
86
+
87
+ get_num_gpus = _base.get_num_gpus
88
+ get_tf_dtype = _performance.get_tf_dtype
89
+ get_loss_scale = _performance.get_loss_scale
90
+ DTYPE_MAP = _performance.DTYPE_MAP
91
+ require_cloud_storage = _device.require_cloud_storage
92
+
93
+ def _get_nondefault_flags_as_dict():
94
+ """Returns the nondefault flags as a dict from flag name to value."""
95
+ nondefault_flags = {}
96
+ for flag_name in flags.FLAGS:
97
+ flag_value = getattr(flags.FLAGS, flag_name)
98
+ if (flag_name != flags.FLAGS[flag_name].short_name and
99
+ flag_value != flags.FLAGS[flag_name].default):
100
+ nondefault_flags[flag_name] = flag_value
101
+ return nondefault_flags
102
+
103
+
104
+ def get_nondefault_flags_as_str():
105
+ """Returns flags as a string that can be passed as command line arguments.
106
+
107
+ E.g., returns: "--batch_size=256 --use_synthetic_data" for the following code
108
+ block:
109
+
110
+ ```
111
+ flags.FLAGS.batch_size = 256
112
+ flags.FLAGS.use_synthetic_data = True
113
+ print(get_nondefault_flags_as_str())
114
+ ```
115
+
116
+ Only flags with nondefault values are returned, as passing default flags as
117
+ command line arguments has no effect.
118
+
119
+ Returns:
120
+ A string with the flags, that can be passed as command line arguments to a
121
+ program to use the flags.
122
+ """
123
+ nondefault_flags = _get_nondefault_flags_as_dict()
124
+ flag_strings = []
125
+ for name, value in sorted(nondefault_flags.items()):
126
+ if isinstance(value, bool):
127
+ flag_str = '--{}'.format(name) if value else '--no{}'.format(name)
128
+ elif isinstance(value, list):
129
+ flag_str = '--{}={}'.format(name, ','.join(value))
130
+ else:
131
+ flag_str = '--{}={}'.format(name, value)
132
+ flag_strings.append(flag_str)
133
+ return ' '.join(shlex_quote(flag_str) for flag_str in flag_strings)
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/flags/guidelines.md ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Using flags in official models
2
+
3
+ 1. **All common flags must be incorporated in the models.**
4
+
5
+ Common flags (i.e. batch_size, model_dir, etc.) are provided by various flag definition functions,
6
+ and channeled through `official.utils.flags.core`. For instance to define common supervised
7
+ learning parameters one could use the following code:
8
+
9
+ ```$xslt
10
+ from absl import app as absl_app
11
+ from absl import flags
12
+
13
+ from TensorFlow.utils.flags import core as flags_core
14
+
15
+
16
+ def define_flags():
17
+ flags_core.define_base()
18
+ flags.adopt_key_flags(flags_core)
19
+
20
+
21
+ def main(_):
22
+ flags_obj = flags.FLAGS
23
+ print(flags_obj)
24
+
25
+
26
+ if __name__ == "__main__"
27
+ absl_app.run(main)
28
+ ```
29
+ 2. **Validate flag values.**
30
+
31
+ See the [Validators](#validators) section for implementation details.
32
+
33
+ Validators in the official model repo should not access the file system, such as verifying
34
+ that files exist, due to the strict ordering requirements.
35
+
36
+ 3. **Flag values should not be mutated.**
37
+
38
+ Instead of mutating flag values, use getter functions to return the desired values. An example
39
+ getter function is `get_tf_dtype` function below:
40
+
41
+ ```
42
+ # Map string to TensorFlow dtype
43
+ DTYPE_MAP = {
44
+ "fp16": tf.float16,
45
+ "fp32": tf.float32,
46
+ }
47
+
48
+ def get_tf_dtype(flags_obj):
49
+ if getattr(flags_obj, "fp16_implementation", None) == "graph_rewrite":
50
+ # If the graph_rewrite is used, we build the graph with fp32, and let the
51
+ # graph rewrite change ops to fp16.
52
+ return tf.float32
53
+ return DTYPE_MAP[flags_obj.dtype]
54
+
55
+
56
+ def main(_):
57
+ flags_obj = flags.FLAGS()
58
+
59
+ # Do not mutate flags_obj
60
+ # if flags_obj.fp16_implementation == "graph_rewrite":
61
+ # flags_obj.dtype = "float32" # Don't do this
62
+
63
+ print(get_tf_dtype(flags_obj))
64
+ ...
65
+ ```
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/misc/callstack_sampler.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A simple Python callstack sampler."""
2
+
3
+ import contextlib
4
+ import datetime
5
+ import signal
6
+ import traceback
7
+
8
+
9
+ class CallstackSampler(object):
10
+ """A simple signal-based Python callstack sampler.
11
+ """
12
+
13
+ def __init__(self, interval=None):
14
+ self.stacks = []
15
+ self.interval = 0.001 if interval is None else interval
16
+
17
+ def _sample(self, signum, frame):
18
+ """Samples the current stack."""
19
+ del signum
20
+ stack = traceback.extract_stack(frame)
21
+ formatted_stack = []
22
+ formatted_stack.append(datetime.datetime.utcnow())
23
+ for filename, lineno, function_name, text in stack:
24
+ formatted_frame = '{}:{}({})({})'.format(filename, lineno, function_name,
25
+ text)
26
+ formatted_stack.append(formatted_frame)
27
+ self.stacks.append(formatted_stack)
28
+ signal.setitimer(signal.ITIMER_VIRTUAL, self.interval, 0)
29
+
30
+ @contextlib.contextmanager
31
+ def profile(self):
32
+ signal.signal(signal.SIGVTALRM, self._sample)
33
+ signal.setitimer(signal.ITIMER_VIRTUAL, self.interval, 0)
34
+ try:
35
+ yield
36
+ finally:
37
+ signal.setitimer(signal.ITIMER_VIRTUAL, 0)
38
+
39
+ def save(self, fname):
40
+ with open(fname, 'w') as f:
41
+ for s in self.stacks:
42
+ for l in s:
43
+ f.write('%s\n' % l)
44
+ f.write('\n')
45
+
46
+
47
+ @contextlib.contextmanager
48
+ def callstack_sampling(filename, interval=None):
49
+ """Periodically samples the Python callstack.
50
+
51
+ Args:
52
+ filename: the filename
53
+ interval: the sampling interval, in seconds. Defaults to 0.001.
54
+
55
+ Yields:
56
+ nothing
57
+ """
58
+ sampler = CallstackSampler(interval=interval)
59
+ with sampler.profile():
60
+ yield
61
+ sampler.save(filename)
62
+
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/testing/__init__.py ADDED
File without changes
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/bert/implementations/TensorFlow/utils/testing/benchmark_wrappers.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Lint as: python3
2
+ """Utils to annotate and trace benchmarks."""
3
+
4
+ from __future__ import absolute_import
5
+ from __future__ import division
6
+ from __future__ import print_function
7
+
8
+ from absl import flags
9
+ from absl import logging
10
+ from absl.testing import flagsaver
11
+
12
+ FLAGS = flags.FLAGS
13
+
14
+ flags.DEFINE_multi_string(
15
+ 'benchmark_method_flags', None,
16
+ 'Optional list of runtime flags of the form key=value. Specify '
17
+ 'multiple times to specify different flags. These will override the FLAGS '
18
+ 'object directly after hardcoded settings in individual benchmark methods '
19
+ 'before they call _run_and_report benchmark. Example if we set '
20
+ '--benchmark_method_flags=train_steps=10 and a benchmark method hardcodes '
21
+ 'FLAGS.train_steps=10000 and later calls _run_and_report_benchmark, '
22
+ 'it\'ll only run for 10 steps. This is useful for '
23
+ 'debugging/profiling workflows.')
24
+
25
+
26
+ def enable_runtime_flags(decorated_func):
27
+ """Sets attributes from --benchmark_method_flags for method execution.
28
+
29
+ @enable_runtime_flags decorator temporarily adds flags passed in via
30
+ --benchmark_method_flags and runs the decorated function in that context.
31
+
32
+ A user can set --benchmark_method_flags=train_steps=5 to run the benchmark
33
+ method in the snippet below with FLAGS.train_steps=5 for debugging (without
34
+ modifying the benchmark code).
35
+
36
+ class ModelBenchmark():
37
+
38
+ @benchmark_wrappers.enable_runtime_flags
39
+ def _run_and_report_benchmark(self):
40
+ # run benchmark ...
41
+ # report benchmark results ...
42
+
43
+ def benchmark_method(self):
44
+ FLAGS.train_steps = 1000
45
+ ...
46
+ self._run_and_report_benchmark()
47
+
48
+ Args:
49
+ decorated_func: The method that runs the benchmark after previous setup
50
+ execution that set some flags.
51
+
52
+ Returns:
53
+ new_func: The same method which executes in a temporary context where flag
54
+ overrides from --benchmark_method_flags are active.
55
+ """
56
+
57
+ def runner(*args, **kwargs):
58
+ """Creates a temporary context to activate --benchmark_method_flags."""
59
+ if FLAGS.benchmark_method_flags:
60
+ saved_flag_values = flagsaver.save_flag_values()
61
+ for key_value in FLAGS.benchmark_method_flags:
62
+ key, value = key_value.split('=', 1)
63
+ try:
64
+ numeric_float = float(value)
65
+ numeric_int = int(numeric_float)
66
+ if abs(numeric_int) == abs(numeric_float):
67
+ flag_value = numeric_int
68
+ else:
69
+ flag_value = numeric_float
70
+ except ValueError:
71
+ flag_value = value
72
+ logging.info('Setting --%s=%s', key, flag_value)
73
+ setattr(FLAGS, key, flag_value)
74
+ else:
75
+ saved_flag_values = None
76
+ try:
77
+ result = decorated_func(*args, **kwargs)
78
+ return result
79
+ finally:
80
+ if saved_flag_values:
81
+ flagsaver.restore_flag_values(saved_flag_values)
82
+
83
+ return runner
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/LICENSE ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2021 Habana Labs, Ltd. an Intel Company
4
+ Copyright (c) Soumith Chintala 2016,
5
+ All rights reserved.
6
+
7
+ Redistribution and use in source and binary forms, with or without
8
+ modification, are permitted provided that the following conditions are met:
9
+
10
+ * Redistributions of source code must retain the above copyright notice, this
11
+ list of conditions and the following disclaimer.
12
+
13
+ * Redistributions in binary form must reproduce the above copyright notice,
14
+ this list of conditions and the following disclaimer in the documentation
15
+ and/or other materials provided with the distribution.
16
+
17
+ * Neither the name of the copyright holder nor the names of its
18
+ contributors may be used to endorse or promote products derived from
19
+ this software without specific prior written permission.
20
+
21
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
25
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/mlperf_variable_map.json ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "conv1.weight": "conv0_weight",
3
+ "bn1.weight": "bn0_gamma",
4
+ "bn1.bias": "bn0_beta",
5
+ "layer1.0.conv1.weight": "stage1_unit1_conv1_weight",
6
+ "layer1.0.bn1.weight": "stage1_unit1_bn1_gamma",
7
+ "layer1.0.bn1.bias": "stage1_unit1_bn1_beta",
8
+ "layer1.0.conv2.weight": "stage1_unit1_conv2_weight",
9
+ "layer1.0.bn2.weight": "stage1_unit1_bn2_gamma",
10
+ "layer1.0.bn2.bias": "stage1_unit1_bn2_beta",
11
+ "layer1.0.conv3.weight": "stage1_unit1_conv3_weight",
12
+ "layer1.0.bn3.weight": "stage1_unit1_bn3_gamma",
13
+ "layer1.0.bn3.bias": "stage1_unit1_bn3_beta",
14
+ "layer1.0.downsample.0.weight": "stage1_unit1_conv1sc_weight",
15
+ "layer1.0.downsample.1.weight": "stage1_unit1_bnsc_gamma",
16
+ "layer1.0.downsample.1.bias": "stage1_unit1_bnsc_beta",
17
+ "layer1.1.conv1.weight": "stage1_unit2_conv1_weight",
18
+ "layer1.1.bn1.weight": "stage1_unit2_bn1_gamma",
19
+ "layer1.1.bn1.bias": "stage1_unit2_bn1_beta",
20
+ "layer1.1.conv2.weight": "stage1_unit2_conv2_weight",
21
+ "layer1.1.bn2.weight": "stage1_unit2_bn2_gamma",
22
+ "layer1.1.bn2.bias": "stage1_unit2_bn2_beta",
23
+ "layer1.1.conv3.weight": "stage1_unit2_conv3_weight",
24
+ "layer1.1.bn3.weight": "stage1_unit2_bn3_gamma",
25
+ "layer1.1.bn3.bias": "stage1_unit2_bn3_beta",
26
+ "layer1.2.conv1.weight": "stage1_unit3_conv1_weight",
27
+ "layer1.2.bn1.weight": "stage1_unit3_bn1_gamma",
28
+ "layer1.2.bn1.bias": "stage1_unit3_bn1_beta",
29
+ "layer1.2.conv2.weight": "stage1_unit3_conv2_weight",
30
+ "layer1.2.bn2.weight": "stage1_unit3_bn2_gamma",
31
+ "layer1.2.bn2.bias": "stage1_unit3_bn2_beta",
32
+ "layer1.2.conv3.weight": "stage1_unit3_conv3_weight",
33
+ "layer1.2.bn3.weight": "stage1_unit3_bn3_gamma",
34
+ "layer1.2.bn3.bias": "stage1_unit3_bn3_beta",
35
+ "layer2.0.conv1.weight": "stage2_unit1_conv1_weight",
36
+ "layer2.0.bn1.weight": "stage2_unit1_bn1_gamma",
37
+ "layer2.0.bn1.bias": "stage2_unit1_bn1_beta",
38
+ "layer2.0.conv2.weight": "stage2_unit1_conv2_weight",
39
+ "layer2.0.bn2.weight": "stage2_unit1_bn2_gamma",
40
+ "layer2.0.bn2.bias": "stage2_unit1_bn2_beta",
41
+ "layer2.0.conv3.weight": "stage2_unit1_conv3_weight",
42
+ "layer2.0.bn3.weight": "stage2_unit1_bn3_gamma",
43
+ "layer2.0.bn3.bias": "stage2_unit1_bn3_beta",
44
+ "layer2.0.downsample.0.weight": "stage2_unit1_conv1sc_weight",
45
+ "layer2.0.downsample.1.weight": "stage2_unit1_bnsc_gamma",
46
+ "layer2.0.downsample.1.bias": "stage2_unit1_bnsc_beta",
47
+ "layer2.1.conv1.weight": "stage2_unit2_conv1_weight",
48
+ "layer2.1.bn1.weight": "stage2_unit2_bn1_gamma",
49
+ "layer2.1.bn1.bias": "stage2_unit2_bn1_beta",
50
+ "layer2.1.conv2.weight": "stage2_unit2_conv2_weight",
51
+ "layer2.1.bn2.weight": "stage2_unit2_bn2_gamma",
52
+ "layer2.1.bn2.bias": "stage2_unit2_bn2_beta",
53
+ "layer2.1.conv3.weight": "stage2_unit2_conv3_weight",
54
+ "layer2.1.bn3.weight": "stage2_unit2_bn3_gamma",
55
+ "layer2.1.bn3.bias": "stage2_unit2_bn3_beta",
56
+ "layer2.2.conv1.weight": "stage2_unit3_conv1_weight",
57
+ "layer2.2.bn1.weight": "stage2_unit3_bn1_gamma",
58
+ "layer2.2.bn1.bias": "stage2_unit3_bn1_beta",
59
+ "layer2.2.conv2.weight": "stage2_unit3_conv2_weight",
60
+ "layer2.2.bn2.weight": "stage2_unit3_bn2_gamma",
61
+ "layer2.2.bn2.bias": "stage2_unit3_bn2_beta",
62
+ "layer2.2.conv3.weight": "stage2_unit3_conv3_weight",
63
+ "layer2.2.bn3.weight": "stage2_unit3_bn3_gamma",
64
+ "layer2.2.bn3.bias": "stage2_unit3_bn3_beta",
65
+ "layer2.3.conv1.weight": "stage2_unit4_conv1_weight",
66
+ "layer2.3.bn1.weight": "stage2_unit4_bn1_gamma",
67
+ "layer2.3.bn1.bias": "stage2_unit4_bn1_beta",
68
+ "layer2.3.conv2.weight": "stage2_unit4_conv2_weight",
69
+ "layer2.3.bn2.weight": "stage2_unit4_bn2_gamma",
70
+ "layer2.3.bn2.bias": "stage2_unit4_bn2_beta",
71
+ "layer2.3.conv3.weight": "stage2_unit4_conv3_weight",
72
+ "layer2.3.bn3.weight": "stage2_unit4_bn3_gamma",
73
+ "layer2.3.bn3.bias": "stage2_unit4_bn3_beta",
74
+ "layer3.0.conv1.weight": "stage3_unit1_conv1_weight",
75
+ "layer3.0.bn1.weight": "stage3_unit1_bn1_gamma",
76
+ "layer3.0.bn1.bias": "stage3_unit1_bn1_beta",
77
+ "layer3.0.conv2.weight": "stage3_unit1_conv2_weight",
78
+ "layer3.0.bn2.weight": "stage3_unit1_bn2_gamma",
79
+ "layer3.0.bn2.bias": "stage3_unit1_bn2_beta",
80
+ "layer3.0.conv3.weight": "stage3_unit1_conv3_weight",
81
+ "layer3.0.bn3.weight": "stage3_unit1_bn3_gamma",
82
+ "layer3.0.bn3.bias": "stage3_unit1_bn3_beta",
83
+ "layer3.0.downsample.0.weight": "stage3_unit1_conv1sc_weight",
84
+ "layer3.0.downsample.1.weight": "stage3_unit1_bnsc_gamma",
85
+ "layer3.0.downsample.1.bias": "stage3_unit1_bnsc_beta",
86
+ "layer3.1.conv1.weight": "stage3_unit2_conv1_weight",
87
+ "layer3.1.bn1.weight": "stage3_unit2_bn1_gamma",
88
+ "layer3.1.bn1.bias": "stage3_unit2_bn1_beta",
89
+ "layer3.1.conv2.weight": "stage3_unit2_conv2_weight",
90
+ "layer3.1.bn2.weight": "stage3_unit2_bn2_gamma",
91
+ "layer3.1.bn2.bias": "stage3_unit2_bn2_beta",
92
+ "layer3.1.conv3.weight": "stage3_unit2_conv3_weight",
93
+ "layer3.1.bn3.weight": "stage3_unit2_bn3_gamma",
94
+ "layer3.1.bn3.bias": "stage3_unit2_bn3_beta",
95
+ "layer3.2.conv1.weight": "stage3_unit3_conv1_weight",
96
+ "layer3.2.bn1.weight": "stage3_unit3_bn1_gamma",
97
+ "layer3.2.bn1.bias": "stage3_unit3_bn1_beta",
98
+ "layer3.2.conv2.weight": "stage3_unit3_conv2_weight",
99
+ "layer3.2.bn2.weight": "stage3_unit3_bn2_gamma",
100
+ "layer3.2.bn2.bias": "stage3_unit3_bn2_beta",
101
+ "layer3.2.conv3.weight": "stage3_unit3_conv3_weight",
102
+ "layer3.2.bn3.weight": "stage3_unit3_bn3_gamma",
103
+ "layer3.2.bn3.bias": "stage3_unit3_bn3_beta",
104
+ "layer3.3.conv1.weight": "stage3_unit4_conv1_weight",
105
+ "layer3.3.bn1.weight": "stage3_unit4_bn1_gamma",
106
+ "layer3.3.bn1.bias": "stage3_unit4_bn1_beta",
107
+ "layer3.3.conv2.weight": "stage3_unit4_conv2_weight",
108
+ "layer3.3.bn2.weight": "stage3_unit4_bn2_gamma",
109
+ "layer3.3.bn2.bias": "stage3_unit4_bn2_beta",
110
+ "layer3.3.conv3.weight": "stage3_unit4_conv3_weight",
111
+ "layer3.3.bn3.weight": "stage3_unit4_bn3_gamma",
112
+ "layer3.3.bn3.bias": "stage3_unit4_bn3_beta",
113
+ "layer3.4.conv1.weight": "stage3_unit5_conv1_weight",
114
+ "layer3.4.bn1.weight": "stage3_unit5_bn1_gamma",
115
+ "layer3.4.bn1.bias": "stage3_unit5_bn1_beta",
116
+ "layer3.4.conv2.weight": "stage3_unit5_conv2_weight",
117
+ "layer3.4.bn2.weight": "stage3_unit5_bn2_gamma",
118
+ "layer3.4.bn2.bias": "stage3_unit5_bn2_beta",
119
+ "layer3.4.conv3.weight": "stage3_unit5_conv3_weight",
120
+ "layer3.4.bn3.weight": "stage3_unit5_bn3_gamma",
121
+ "layer3.4.bn3.bias": "stage3_unit5_bn3_beta",
122
+ "layer3.5.conv1.weight": "stage3_unit6_conv1_weight",
123
+ "layer3.5.bn1.weight": "stage3_unit6_bn1_gamma",
124
+ "layer3.5.bn1.bias": "stage3_unit6_bn1_beta",
125
+ "layer3.5.conv2.weight": "stage3_unit6_conv2_weight",
126
+ "layer3.5.bn2.weight": "stage3_unit6_bn2_gamma",
127
+ "layer3.5.bn2.bias": "stage3_unit6_bn2_beta",
128
+ "layer3.5.conv3.weight": "stage3_unit6_conv3_weight",
129
+ "layer3.5.bn3.weight": "stage3_unit6_bn3_gamma",
130
+ "layer3.5.bn3.bias": "stage3_unit6_bn3_beta",
131
+ "layer4.0.conv1.weight": "stage4_unit1_conv1_weight",
132
+ "layer4.0.bn1.weight": "stage4_unit1_bn1_gamma",
133
+ "layer4.0.bn1.bias": "stage4_unit1_bn1_beta",
134
+ "layer4.0.conv2.weight": "stage4_unit1_conv2_weight",
135
+ "layer4.0.bn2.weight": "stage4_unit1_bn2_gamma",
136
+ "layer4.0.bn2.bias": "stage4_unit1_bn2_beta",
137
+ "layer4.0.conv3.weight": "stage4_unit1_conv3_weight",
138
+ "layer4.0.bn3.weight": "stage4_unit1_bn3_gamma",
139
+ "layer4.0.bn3.bias": "stage4_unit1_bn3_beta",
140
+ "layer4.0.downsample.0.weight": "stage4_unit1_conv1sc_weight",
141
+ "layer4.0.downsample.1.weight": "stage4_unit1_bnsc_gamma",
142
+ "layer4.0.downsample.1.bias": "stage4_unit1_bnsc_beta",
143
+ "layer4.1.conv1.weight": "stage4_unit2_conv1_weight",
144
+ "layer4.1.bn1.weight": "stage4_unit2_bn1_gamma",
145
+ "layer4.1.bn1.bias": "stage4_unit2_bn1_beta",
146
+ "layer4.1.conv2.weight": "stage4_unit2_conv2_weight",
147
+ "layer4.1.bn2.weight": "stage4_unit2_bn2_gamma",
148
+ "layer4.1.bn2.bias": "stage4_unit2_bn2_beta",
149
+ "layer4.1.conv3.weight": "stage4_unit2_conv3_weight",
150
+ "layer4.1.bn3.weight": "stage4_unit2_bn3_gamma",
151
+ "layer4.1.bn3.bias": "stage4_unit2_bn3_beta",
152
+ "layer4.2.conv1.weight": "stage4_unit3_conv1_weight",
153
+ "layer4.2.bn1.weight": "stage4_unit3_bn1_gamma",
154
+ "layer4.2.bn1.bias": "stage4_unit3_bn1_beta",
155
+ "layer4.2.conv2.weight": "stage4_unit3_conv2_weight",
156
+ "layer4.2.bn2.weight": "stage4_unit3_bn2_gamma",
157
+ "layer4.2.bn2.bias": "stage4_unit3_bn2_beta",
158
+ "layer4.2.conv3.weight": "stage4_unit3_conv3_weight",
159
+ "layer4.2.bn3.weight": "stage4_unit3_bn3_gamma",
160
+ "layer4.2.bn3.bias": "stage4_unit3_bn3_beta",
161
+ "fc.weight": "fc1_weight",
162
+ "fc.bias": "fc1_bias"
163
+ }
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/model/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .resnet import *
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/model/optimizer.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2022 Habana Labs, Ltd. an Intel Company
2
+
3
+ import torch
4
+ from torch.optim.lr_scheduler import _LRScheduler
5
+
6
+ class PolynomialDecayWithWarmup(_LRScheduler):
7
+ """Polynomial learning rate decay until step reach to max_decay_step
8
+
9
+ Args
10
+ optimizer (Optimizer): Wrapped optimizer.
11
+ max_decay_steps: after this step, we stop decreasing learning rate
12
+ end_learning_rate: scheduler stoping learning rate decay, value of learning rate must be this value
13
+ power: The power of the polynomial.
14
+ """
15
+
16
+ def __init__(self, optimizer, batch_size, steps_per_epoch, train_steps, initial_learning_rate=9.0, warmup_epochs=3,
17
+ end_learning_rate=0.0001, power=2.0, lars_decay_epochs=36, mlperf_mlloger=None, mlperf_mllog=None, opt_name=None):
18
+ self.last_step = 0
19
+ self.steps_per_epoch = steps_per_epoch
20
+ self.train_steps = train_steps
21
+ self.initial_learning_rate = initial_learning_rate
22
+ self.warmup_epochs = warmup_epochs
23
+ self.end_learning_rate = end_learning_rate
24
+ self.power = power
25
+ self.warmup_steps = warmup_epochs * (steps_per_epoch - 1)
26
+ self.decay_steps = lars_decay_epochs * (steps_per_epoch - 1) - self.warmup_steps + 1
27
+ self.opt_name = opt_name.lower()
28
+
29
+ mlperf_mlloger.event(key=mlperf_mllog.constants.LARS_OPT_END_LR, value=self.end_learning_rate)
30
+ mlperf_mlloger.event(key=mlperf_mllog.constants.LARS_OPT_LR_DECAY_STEPS, value=int(self.decay_steps))
31
+ mlperf_mlloger.event(key=mlperf_mllog.constants.LARS_OPT_LR_DECAY_POLY_POWER, value=power)
32
+ mlperf_mlloger.event(key=self.opt_name+'_'+mlperf_mllog.constants.OPT_LR_WARMUP_EPOCHS, value=float(self.warmup_epochs))
33
+ mlperf_mlloger.event(key=self.opt_name+'_'+mlperf_mllog.constants.OPT_BASE_LR, value=self.initial_learning_rate)
34
+
35
+ super().__init__(optimizer)
36
+
37
+ def get_lr(self):
38
+ warmup_steps = self.warmup_steps
39
+ warmup_rate = (
40
+ self.initial_learning_rate * self.last_step / warmup_steps)
41
+
42
+ poly_steps = self.last_step - warmup_steps
43
+ poly_steps = poly_steps if poly_steps > 1 else 1
44
+
45
+ poly_rate = (self.initial_learning_rate - self.end_learning_rate) * \
46
+ ((1 - poly_steps / self.decay_steps) **
47
+ (self.power)) + self.end_learning_rate
48
+
49
+ decay_rate = warmup_rate if self.last_step <= warmup_steps else poly_rate
50
+ return decay_rate
51
+
52
+ def step(self, step=None):
53
+ if step is None:
54
+ step = self.last_step + 1
55
+ self.last_step = step if step != 0 else 1
56
+ if self.last_step <= self.decay_steps + self.warmup_steps:
57
+ decay_lrs = [self.get_lr()]
58
+ for param_group, lr in zip(self.optimizer.param_groups, decay_lrs):
59
+ param_group['lr'] = lr
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/ops_fp32_Resnet.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ cross_entropy_loss
2
+ log_softmax
3
+ nll_loss
4
+ softmax
5
+ topk
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/HLS-Gaudi2-PT/PyTorch/requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ mpi4py>=3.0.3
2
+ scipy>=1.7.1
3
+ colorlog==6.6.0
4
+ git+https://github.com/mlperf/[email protected]
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/debug.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ ###############################################################################
16
+ # Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company
17
+ ###############################################################################
18
+
19
+ from absl import flags
20
+ from absl import logging
21
+ from tensorflow.core.protobuf import debug_event_pb2
22
+ from tensorflow.python.debug.lib import debug_events_writer
23
+ from tensorflow.python.framework import op_callbacks
24
+ from tensorflow.python.ops import gen_debug_ops
25
+ import tensorflow as tf
26
+ import re
27
+ import json
28
+
29
+ flags.DEFINE_string(name='dump_config', default=None, help='Defines config for tensor dumping')
30
+
31
+
32
+ class _DumpCallback(object):
33
+ def __init__(self, dump_root, tensor_debug_mode, circular_buffer_size, op_regex):
34
+ self._dump_root = dump_root
35
+ self._tensor_debug_mode = debug_event_pb2.TensorDebugMode.Value(tensor_debug_mode)
36
+ self._circular_buffer_size = circular_buffer_size
37
+ self._op_regex = re.compile(op_regex) if isinstance(op_regex, str) else op_regex
38
+ self._tfdbg_run_id = ''
39
+ self._dump_op_counter = 0
40
+
41
+ debug_writer_args = {
42
+ "dump_root" : self._dump_root,
43
+ "circular_buffer_size": self._circular_buffer_size
44
+ }
45
+
46
+ if tf.__version__.startswith("2.4"):
47
+ debug_writer_args["tfdbg_run_id"] = self._tfdbg_run_id
48
+
49
+ self._writer = debug_events_writer.DebugEventsWriter(**debug_writer_args)
50
+
51
+ def callback(self, op_type, inputs, attrs, outputs, op_name=None, graph=None):
52
+ if op_name is not None and self._op_regex.match(op_name):
53
+ graph_name = "missing-graph-name"
54
+ if graph is not None and hasattr(graph, "name"):
55
+ graph_name=graph.name
56
+
57
+ logging.info("Adding dump op for '%s' of type '%s' from graph '%s'" %(op_name, op_type, graph_name))
58
+
59
+ new_outputs = []
60
+
61
+ for output_slot, output in enumerate(outputs):
62
+ debug_identity_op_kwargs = {
63
+ "tfdbg_context_id": graph_name,
64
+ "op_name": op_name,
65
+ "output_slot": output_slot,
66
+ "tensor_debug_mode": self._tensor_debug_mode,
67
+ "debug_urls": ["file://%s" % self._dump_root],
68
+ "name": "dump_%d" % self._dump_op_counter
69
+ }
70
+
71
+ if tf.__version__.startswith("2.4"):
72
+ debug_identity_op_kwargs["circular_buffer_size"] = self._circular_buffer_size
73
+ debug_identity_op_kwargs["tfdbg_run_id"] = self._tfdbg_run_id
74
+
75
+ self._dump_op_counter = self._dump_op_counter + 1
76
+ new_outputs.append(gen_debug_ops.debug_identity_v2(output, **debug_identity_op_kwargs))
77
+
78
+ return new_outputs
79
+ else:
80
+ return None
81
+
82
+ def __enter__(self, *args, **kwargs):
83
+ op_callbacks.add_op_callback(self.callback)
84
+ logging.info("Enabled tensor dumping")
85
+
86
+ def __exit__(self, *args, **kwargs):
87
+ op_callbacks.remove_op_callback(self.callback)
88
+ logging.info("Disabled tensor dumping")
89
+
90
+ def __del__(self):
91
+ self._writer.Close()
92
+
93
+ class _Dummy(object):
94
+ def __enter__(self, *args, **kwargs):
95
+ pass
96
+ def __exit__(self, *args, **kwargs):
97
+ pass
98
+
99
+ def dump_callback(config_file=None):
100
+ if config_file is not None:
101
+ kwargs = json.load(open(config_file, 'r'))
102
+ return _DumpCallback(**kwargs)
103
+ try:
104
+ kwargs = json.load(open(flags.FLAGS.dump_config, 'r'))
105
+ return _DumpCallback(**kwargs)
106
+ except:
107
+ return _Dummy()
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/modeling/__init__.py ADDED
File without changes
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/modeling/performance.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Lint as: python3
2
+ # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ # ==============================================================================
16
+ """Functions and classes related to training performance."""
17
+
18
+ import tensorflow as tf
19
+
20
+
21
+ def configure_optimizer(optimizer,
22
+ use_float16=False,
23
+ use_graph_rewrite=False,
24
+ loss_scale="dynamic"):
25
+ """Configures optimizer object with performance options."""
26
+ if use_float16:
27
+ # Wraps optimizer with a LossScaleOptimizer. This is done automatically
28
+ # in compile() with the "mixed_float16" policy, but since we do not call
29
+ # compile(), we must wrap the optimizer manually.
30
+ optimizer = (
31
+ tf.keras.mixed_precision.LossScaleOptimizer(
32
+ optimizer, loss_scale=loss_scale))
33
+ if use_graph_rewrite:
34
+ # Note: the model dtype must be 'float32', which will ensure
35
+ # tf.ckeras.mixed_precision and
36
+ # tf.compat.v1.mixed_precision.enable_mixed_precision_graph_rewrite do not double
37
+ # up.
38
+ optimizer = tf.compat.v1.mixed_precision.enable_mixed_precision_graph_rewrite(
39
+ optimizer)
40
+ return optimizer
41
+
42
+
43
+ def set_mixed_precision_policy(dtype, loss_scale=None):
44
+ """Sets mix precision policy."""
45
+ if dtype == tf.float16:
46
+ policy = tf.keras.mixed_precision.Policy(
47
+ 'mixed_float16', loss_scale=loss_scale)
48
+ tf.keras.mixed_precision.set_global_policy(policy)
49
+ elif dtype == tf.bfloat16:
50
+ policy = tf.keras.mixed_precision.Policy(
51
+ 'mixed_bfloat16')
52
+ tf.keras.mixed_precision.set_global_policy(policy)
53
+ elif dtype == tf.float32:
54
+ tf.keras.mixed_precision.set_global_policy('float32')
55
+ else:
56
+ raise ValueError("Unexpected dtype: %s" % dtype)
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/tb_utils.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import tensorflow as tf
4
+ from copy import deepcopy
5
+ from tensorboard.plugins.hparams import api as hp
6
+ from tensorflow.python.eager import context
7
+ from tensorflow.keras import backend as K
8
+ from tensorflow.python.ops import summary_ops_v2
9
+ from tensorflow.python.summary import summary as tf_summary
10
+ from tensorflow.python.training.summary_io import SummaryWriterCache
11
+ from tensorflow.compat.v1.keras.callbacks import TensorBoard, Callback
12
+
13
+
14
+ def _remove_prefix(s, prefix):
15
+ if s.startswith(prefix):
16
+ s = s[len(prefix):]
17
+ return s
18
+
19
+
20
+ def _parse_precision():
21
+ flag = os.environ.get('TF_BF16_CONVERSION', '0')
22
+ flag = flag.lower()
23
+ try:
24
+ value = int(flag)
25
+ except:
26
+ value = -1
27
+
28
+ if flag == 'false' or value == 0:
29
+ return 'fp32'
30
+ elif flag == 'true' or value == 1:
31
+ return 'bf16'
32
+ return flag
33
+
34
+
35
+ def _set_precision_if_missing(hparams: dict):
36
+ if 'precision' not in hparams:
37
+ hparams['precision'] = _parse_precision()
38
+ return hparams
39
+
40
+
41
+ def _copy_and_clean_hparams(hparams: dict):
42
+ hparams_ = dict()
43
+ for name, value in hparams.items():
44
+ if isinstance(value, (str, bool, int, float)):
45
+ hparams_[name] = value
46
+ continue
47
+
48
+ try:
49
+ hparams_[name] = str(value)
50
+ tf.compat.v1.logging.info(
51
+ f'Type of parameter "{name}" is not one of (bool, int, float, str). '
52
+ 'It will be saved as a string.')
53
+ except:
54
+ tf.compat.v1.logging.info(
55
+ f'Conversion of parameter "{name}" to string failed. '
56
+ 'Parameter will not be saved.')
57
+
58
+ return hparams_
59
+
60
+
61
+ def write_hparams_v1(writer, hparams: dict):
62
+ hparams = _copy_and_clean_hparams(hparams)
63
+ hparams = _set_precision_if_missing(hparams)
64
+
65
+ with tf.compat.v1.Graph().as_default():
66
+ if isinstance(writer, str):
67
+ writer = SummaryWriterCache.get(writer)
68
+ summary = hp.hparams_pb(hparams).SerializeToString()
69
+ writer.add_summary(summary)
70
+
71
+
72
+ def write_hparams_v2(writer, hparams: dict):
73
+ hparams = _copy_and_clean_hparams(hparams)
74
+ hparams = _set_precision_if_missing(hparams)
75
+
76
+ with writer.as_default():
77
+ hp.hparams(hparams)
78
+
79
+
80
+ class ExamplesPerSecondEstimatorHook(tf.compat.v1.train.StepCounterHook):
81
+ """Calculate and report global_step/sec and examples/sec during runtime."""
82
+ # Copy-pasted from tensorflow_estimator/python/estimator/tpu/tpu_estimator.py
83
+
84
+ def __init__(self,
85
+ batch_size=None,
86
+ every_n_steps=1,
87
+ every_n_secs=None,
88
+ output_dir=None,
89
+ summary_writer=None,
90
+ extra_metrics=None,
91
+ log_global_step=False,
92
+ verbose=False):
93
+ super().__init__(
94
+ every_n_steps=every_n_steps,
95
+ every_n_secs=every_n_secs,
96
+ output_dir=output_dir,
97
+ summary_writer=summary_writer)
98
+ self._metrics = extra_metrics or {}
99
+ self._verbose = verbose
100
+ if log_global_step:
101
+ # Because estimator will log global_step/sec by default
102
+ # when log_step_count_steps is not None saving it here
103
+ # would duplicate events in TensorBoard.
104
+ # Use log_global_step=True when RunConfig.log_step_count_step=None
105
+ self._metrics['global_step/sec'] = 1
106
+ if batch_size is not None:
107
+ self._metrics['examples/sec'] = batch_size
108
+
109
+ def _add_summary(self, tag, value, step):
110
+ Summary = tf.compat.v1.Summary
111
+ global_step_summary = Summary(value=[
112
+ Summary.Value(tag=tag, simple_value=value)
113
+ ])
114
+ self._summary_writer.add_summary(global_step_summary, step)
115
+ if self._verbose:
116
+ tf.compat.v1.logging.info(f'{tag}: {value}')
117
+
118
+ def _log_and_record(self, elapsed_steps, elapsed_time, global_step):
119
+ global_step_per_sec = elapsed_steps / elapsed_time
120
+ if self._summary_writer is not None:
121
+ for name, factor in self._metrics.items():
122
+ value = factor * global_step_per_sec
123
+ self._add_summary(name, value, global_step)
124
+
125
+ def after_create_session(self, session, coord):
126
+ self._timer.reset()
127
+
128
+
129
+ class ExamplesPerSecondKerasHookV1(Callback):
130
+ def __init__(self,
131
+ every_n_steps=1,
132
+ every_n_secs=None,
133
+ output_dir=None,
134
+ summary_writer=None,
135
+ batch_size=None):
136
+ self.writer = summary_writer or SummaryWriterCache.get(output_dir)
137
+ self._timer = tf.compat.v1.train.SecondOrStepTimer(
138
+ every_n_secs, every_n_steps)
139
+ self._total_examples = 0
140
+ self._should_trigger = True
141
+ self._batch_size = batch_size
142
+
143
+ def on_train_begin(self, logs=None):
144
+ self._timer.reset()
145
+
146
+ def on_train_batch_begin(self, batch, logs=None):
147
+ self._should_trigger = self._timer.should_trigger_for_step(
148
+ logs.get('batch', batch))
149
+
150
+ def on_train_batch_end(self, batch, logs=None):
151
+ step = logs.get('batch', batch)
152
+ self._total_examples += logs.get('size', 0)
153
+ if self._should_trigger:
154
+ elapsed_time, elapsed_steps = self._timer.update_last_triggered_step(
155
+ step)
156
+ if elapsed_time is not None:
157
+ total_examples = self._total_examples
158
+ if self._batch_size is not None:
159
+ total_examples = self._batch_size * elapsed_steps
160
+ self._log_and_record(
161
+ elapsed_steps, elapsed_time, step, total_examples)
162
+ self._total_examples = 0
163
+
164
+ def _log_and_record(self, elapsed_steps, elapsed_time,
165
+ global_step, total_examples=None):
166
+ Summary = tf.compat.v1.Summary
167
+ global_step_per_sec = elapsed_steps / elapsed_time
168
+ if self.writer is not None:
169
+ global_step_summary = Summary(value=[
170
+ Summary.Value(
171
+ tag='global_step/sec', simple_value=global_step_per_sec)
172
+ ])
173
+ self.writer.add_summary(global_step_summary, global_step)
174
+ if total_examples is not None:
175
+ examples_per_sec = total_examples / elapsed_time
176
+ example_summary = Summary(value=[
177
+ Summary.Value(tag='examples/sec',
178
+ simple_value=examples_per_sec)
179
+ ])
180
+ self.writer.add_summary(example_summary, global_step)
181
+
182
+
183
+ class ExamplesPerSecondKerasHookV2(ExamplesPerSecondKerasHookV1):
184
+ def __init__(self,
185
+ every_n_steps=1,
186
+ every_n_secs=None,
187
+ output_dir=None,
188
+ summary_writer=None,
189
+ batch_size=None):
190
+ writer = summary_writer or summary_ops_v2.create_file_writer_v2(output_dir)
191
+ super().__init__(every_n_steps, every_n_secs, output_dir, writer, batch_size)
192
+
193
+ def _log_and_record(self, elapsed_steps, elapsed_time,
194
+ global_step, total_examples=None):
195
+ global_step_per_sec = elapsed_steps / elapsed_time
196
+ if self.writer is not None:
197
+ with self.writer.as_default(), summary_ops_v2.always_record_summaries():
198
+ summary_ops_v2.scalar('global_step/sec', global_step_per_sec,
199
+ step=global_step)
200
+ if total_examples is not None:
201
+ examples_per_sec = total_examples / elapsed_time
202
+ summary_ops_v2.scalar('examples/sec', examples_per_sec,
203
+ step=global_step)
204
+
205
+
206
+ ExamplesPerSecondKerasHook = ExamplesPerSecondKerasHookV1
207
+
208
+
209
+ class TBSummary(object):
210
+ """
211
+ Creates a proxy for FileWriter for TensorBoard.
212
+
213
+ :param log_dir: - path where experiment is running (usually the same as
214
+ model_dir in Estimator)
215
+ """
216
+
217
+ def __init__(self, log_dir: str):
218
+ super().__init__()
219
+ self._log_dir = log_dir
220
+ self._session = None
221
+
222
+ def __enter__(self):
223
+ self._session = tf.compat.v1.Session()
224
+ return self
225
+
226
+ def __exit__(self, exc_type, exc_val, exc_tb):
227
+ if self._session:
228
+ self._session.close()
229
+ self._session = None
230
+
231
+ def add_scalar(self, tag, value, global_step=None):
232
+ with self._session:
233
+ writer = SummaryWriterCache.get(self._log_dir)
234
+ summary = tf.compat.v1.Summary(
235
+ value=[tf.compat.v1.Summary.Value(tag=tag, simple_value=value)])
236
+ event = tf.compat.v1.Event(summary=summary)
237
+ event.wall_time = time.time()
238
+ event.step = global_step
239
+ writer.add_event(event)
240
+
241
+
242
+ class TensorBoardWithHParamsV1(TensorBoard):
243
+ """
244
+ Adds TensorBoard visualization to training process.
245
+
246
+ Writes training tfevent file into default log directory, but
247
+ stores evaluation in log_dir/eval subdirectory.
248
+ """
249
+
250
+ def __init__(self, hparams, *args, **kwargs):
251
+ super().__init__(*args, **kwargs)
252
+ self.hparams = hparams
253
+ self._train_summary = None
254
+ self._eval_summary = None
255
+
256
+ def _switch_writer(self, mode):
257
+ self.writer = self._train_summary if mode == 'train' else self._eval_summary
258
+
259
+ def _init_writer(self, model):
260
+ """Sets file writer."""
261
+ if context.executing_eagerly():
262
+ raise NotImplementedError('hook does not support eager execution')
263
+
264
+ self._train_summary = SummaryWriterCache.get(self.log_dir)
265
+ self._eval_summary = SummaryWriterCache.get(
266
+ os.path.join(self.log_dir, 'eval'))
267
+ self._switch_writer('train')
268
+
269
+ write_hparams_v1(self.writer, self.hparams)
270
+
271
+ def _write_custom_summaries(self, step, logs=None):
272
+ """
273
+ This methods works on the assumption that metrics containing `val`
274
+ in name are related to validation (that's the default in Keras).
275
+ """
276
+
277
+ logs = logs or {}
278
+ train_logs = {}
279
+ eval_logs = {}
280
+
281
+ for name, value in logs.items():
282
+ if 'val' in name:
283
+ if name.startswith('batch_val_'):
284
+ name = 'batch_' + _remove_prefix(name, 'batch_val_')
285
+ elif name.startswith('epoch_val_'):
286
+ name = _remove_prefix(name, 'epoch_val_')
287
+ eval_logs[name] = value
288
+ else:
289
+ if name.startswith('batch_'):
290
+ name = _remove_prefix(name, 'batch_')
291
+ train_logs[name] = value
292
+
293
+ self._switch_writer('eval')
294
+ super()._write_custom_summaries(step, eval_logs)
295
+ self._switch_writer('train')
296
+ super()._write_custom_summaries(step, train_logs)
297
+
298
+
299
+ class TensorBoardWithHParamsV2(TensorBoard):
300
+ """
301
+ Adds TensorBoard visualization to training process.
302
+
303
+ Writes training tfevent file into default log directory, but
304
+ stores evaluation in log_dir/eval subdirectory.
305
+ """
306
+
307
+ def __init__(self, hparams, *args, **kwargs):
308
+ super().__init__(*args, **kwargs)
309
+ self.hparams = hparams
310
+
311
+ def set_model(self, model):
312
+ """Sets Keras model and writes graph if specified."""
313
+ self.model = model
314
+ self._log_write_dir = self._get_log_write_dir()
315
+
316
+ self._train_dir = self._log_write_dir
317
+ self._train_step = self.model._train_counter # pylint: disable=protected-access
318
+
319
+ self._val_dir = os.path.join(self._log_write_dir, 'eval')
320
+ self._val_step = self.model._test_counter # pylint: disable=protected-access
321
+
322
+ self._writers = {} # Resets writers.
323
+
324
+ self._should_write_train_graph = False
325
+ if self.write_graph:
326
+ self._write_keras_model_summary()
327
+ self._should_write_train_graph = True
328
+ if self.embeddings_freq:
329
+ self._configure_embeddings()
330
+
331
+ write_hparams_v2(self._train_writer, self.hparams)
332
+
333
+ def _log_epoch_metrics(self, epoch, logs):
334
+ """Writes epoch metrics out as scalar summaries.
335
+
336
+ Arguments:
337
+ epoch: Int. The global step to use for TensorBoard.
338
+ logs: Dict. Keys are scalar summary names, values are scalars.
339
+ """
340
+ if not logs:
341
+ return
342
+
343
+ train_logs = {k: v for k,
344
+ v in logs.items() if not k.startswith('val_')}
345
+ val_logs = {k: v for k, v in logs.items() if k.startswith('val_')}
346
+ train_logs = self._collect_learning_rate(train_logs)
347
+
348
+ with summary_ops_v2.always_record_summaries():
349
+ if train_logs:
350
+ with self._train_writer.as_default():
351
+ for name, value in train_logs.items():
352
+ summary_ops_v2.scalar(name, value, step=epoch)
353
+ if val_logs:
354
+ with self._val_writer.as_default():
355
+ for name, value in val_logs.items():
356
+ name = name[4:] # Remove 'val_' prefix.
357
+ summary_ops_v2.scalar(name, value, step=epoch)
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/controller.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """A light weight utilities to train TF2 models."""
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ # from __future__ import google_type_annotations
20
+ from __future__ import print_function
21
+
22
+ import time
23
+ import os
24
+
25
+ from absl import logging
26
+
27
+ import tensorflow.compat.v2 as tf
28
+ from typing import Callable, Dict, Optional, Text
29
+
30
+ from TensorFlow.common.training import utils
31
+
32
+
33
+ class Controller(object):
34
+ """Class that facilitates training and evaluation of models."""
35
+
36
+ def __init__(
37
+ self,
38
+ strategy: Optional[tf.distribute.Strategy] = None,
39
+ train_fn: Optional[Callable[[tf.Tensor],
40
+ Optional[Dict[Text, tf.Tensor]]]] = None,
41
+ eval_fn: Optional[Callable[[tf.Tensor],
42
+ Optional[Dict[Text, tf.Tensor]]]] = None,
43
+ warmup_fn: Optional[Callable[[tf.Tensor],
44
+ Optional[Dict[Text, tf.Tensor]]]] = None,
45
+ global_step: Optional[tf.Variable] = None,
46
+ # Train related
47
+ train_steps: Optional[int] = None,
48
+ steps_per_loop: Optional[int] = None,
49
+ summary_dir: Optional[Text] = None,
50
+ checkpoint_manager: Optional[tf.train.CheckpointManager] = None,
51
+ # summary related
52
+ summary_interval: Optional[int] = None,
53
+ # Evaluation related
54
+ eval_summary_dir: Optional[Text] = None,
55
+ eval_steps: Optional[int] = None,
56
+ eval_interval: Optional[int] = None,
57
+ eval_offset: Optional[int] = 0,
58
+ # Warmup related
59
+ device_warmup_steps: Optional[int] = None,
60
+ train_summary_writer: Optional[tf.summary.SummaryWriter] = None,
61
+ eval_summary_writer: Optional[tf.summary.SummaryWriter] = None):
62
+ """Constructs a `Controller` instance.
63
+
64
+ Args:
65
+ strategy: An instance of `tf.distribute.Strategy`.
66
+ train_fn: A callable defined as `def train_fn(num_steps)`, which
67
+ `num_steps` indicates the number of steps to run for each loop.
68
+ eval_fn: A callable defined as `def eval_fn(num_steps)`, which `num_steps`
69
+ indicates the number of steps for one evaluation.
70
+ global_step: An integer `tf.Variable` indicating the global training step
71
+ number. Usually this can be obtained from `iterations` property of the
72
+ model's optimizer (e.g. `self.optimizer.iterations`), or users can
73
+ create their own global step variable as well. If the users create their
74
+ own global step variable, it is recommended to create the `tf.Variable`
75
+ inside strategy scope, and with
76
+ `aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA`.
77
+ train_steps: The total (maximum) number of training steps to perform.
78
+ steps_per_loop: The number of steps to run in each "inner loop" of
79
+ training (passed to the `num_steps` parameter of `train_fn`).
80
+ summary_dir: The directory to restore and write checkpoints and summaries.
81
+ If None, it will be set to `checkpoint_manager.directory`.
82
+ checkpoint_manager: An instance of `tf.train.CheckpointManager`.
83
+ summary_interval: Step interval for training summaries. Note that this
84
+ argument only applies to the summaries outside the training loop. If the
85
+ value is None, then training summaries are not enabled.
86
+ eval_summary_dir: The directory to write eval summaries. If None, it will
87
+ be set to `summary_dir`.
88
+ eval_steps: Number of steps to run evaluation.
89
+ eval_interval: Step interval for evaluation. If None, will skip evaluation
90
+ in the middle of training. Note that evaluation only happens outside the
91
+ training loop, which the loop iteration is specify by `steps_per_loop`
92
+ parameter.
93
+ eval_offset: Step number of the first evaluation.
94
+ train_summary_writer: Instance of tf.summary.SummaryWriter that should be
95
+ used for saving training summaries to TensorBoard.
96
+ eval_summary_writer: Instance of tf.summary.SummaryWriter that should be
97
+ used for saving evaluation summaries to TensorBoard.
98
+
99
+ Raises:
100
+ ValueError: If both `train_fn` and `eval_fn` are None.
101
+ ValueError: If `train_fn` is not None and `train_steps` is None.
102
+ ValueError: If `steps_per_loop` is None when `train_fn` is provided.
103
+ ValueError: If `steps_per_loop` is not a positive integer.
104
+ """
105
+ if train_fn is None and eval_fn is None:
106
+ raise ValueError("`train_fn` and `eval_fn` should not both be None")
107
+
108
+ # TODO(rxsang): Support training until exhaustion by passing
109
+ # `train_steps=-1`. Currently it cannot be supported with a host training
110
+ # loop because break statements are not supported with distributed dataset.
111
+ if train_fn is not None:
112
+ if train_steps is None:
113
+ raise ValueError("`train_steps` is required when `train_fn` is "
114
+ "provided.")
115
+ if steps_per_loop is None:
116
+ raise ValueError("`steps_per_loop` is required when `train_fn is "
117
+ "provided.")
118
+ if not isinstance(steps_per_loop, int) or steps_per_loop < 1:
119
+ raise ValueError("`steps_per_loop` should be a positive integer")
120
+ if summary_interval is not None and summary_interval <= 0:
121
+ raise ValueError("`summary_interval` should be larger than 0")
122
+
123
+ self.strategy = strategy or tf.distribute.get_strategy()
124
+
125
+ self.train_fn = train_fn
126
+ self.eval_fn = eval_fn
127
+ self.warmup_fn = warmup_fn
128
+ self.global_step = global_step
129
+ self.checkpoint_manager = checkpoint_manager
130
+ self.last_eval_output = None
131
+
132
+ if self.train_fn is not None:
133
+ self.train_steps = train_steps
134
+ self.steps_per_loop = steps_per_loop
135
+ self.summary_dir = summary_dir or checkpoint_manager.directory
136
+
137
+ self.summary_interval = summary_interval
138
+ if train_summary_writer is not None:
139
+ summary_writer = train_summary_writer
140
+ summary_writer = tf.summary.create_file_writer(
141
+ self.summary_dir) if self.summary_interval else None
142
+ # TODO(rxsang): Consider pass SummaryManager directly into Controller for
143
+ # maximum customizability.
144
+ self.summary_manager = utils.SummaryManager(
145
+ summary_writer,
146
+ tf.summary.scalar,
147
+ global_step=self.global_step,
148
+ summary_interval=self.summary_interval)
149
+
150
+ if self.eval_fn is not None:
151
+ if eval_summary_dir is None and self.summary_dir is not None:
152
+ eval_summary_dir = os.path.join(self.summary_dir, 'eval')
153
+ if eval_summary_writer is not None:
154
+ summary_writer = eval_summary_writer
155
+ elif eval_summary_dir:
156
+ summary_writer = tf.summary.create_file_writer(eval_summary_dir)
157
+ else:
158
+ summary_writer = None
159
+ self.eval_summary_manager = utils.SummaryManager(
160
+ summary_writer, tf.summary.scalar, global_step=self.global_step)
161
+
162
+ self.eval_steps = eval_steps
163
+ self.eval_interval = eval_interval
164
+ self.eval_offset = eval_offset
165
+
166
+ # Create and initialize the interval triggers.
167
+ self.eval_trigger = utils.IntervalTrigger(self.eval_interval,
168
+ self.eval_offset)
169
+
170
+ if self.warmup_fn is not None:
171
+ self.device_warmup_steps = device_warmup_steps
172
+
173
+ if self.global_step:
174
+ tf.summary.experimental.set_step(self.global_step)
175
+
176
+ # Restore Model if needed.
177
+ if self.checkpoint_manager is not None:
178
+ model_restored = self._restore_model()
179
+ if not model_restored and self.checkpoint_manager.checkpoint_interval:
180
+ # If the model is not restored from a checkpoint, save an initial
181
+ # checkpoint.
182
+ ckpt_path = self.checkpoint_manager.save(
183
+ checkpoint_number=self.global_step)
184
+ logging.info("Saved checkpoins in %s", ckpt_path)
185
+
186
+ def _restore_model(self, checkpoint_path=None):
187
+ """Restore or initialize the model.
188
+
189
+ Args:
190
+ checkpoint_path: An optional string indicates the checkpoint path to
191
+ restore. If None, will restore from `self.checkpoint_manager`.
192
+
193
+ Returns:
194
+ True if the latest checkpoint is found or restored. Otherwise False.
195
+ """
196
+ with self.strategy.scope():
197
+ # Checkpoint restoring should be inside scope. b/139450638
198
+ if checkpoint_path is not None:
199
+ self.checkpoint_manager.checkpoint.restore(checkpoint_path)
200
+ return True
201
+ return self.checkpoint_manager.restore_or_initialize()
202
+
203
+ def _evaluate_once(self, current_step):
204
+ """Runs the evaluation once."""
205
+ logging.info("Start evaluation at step: %s", current_step)
206
+
207
+ with self.eval_summary_manager.summary_writer.as_default():
208
+ eval_outputs = self.eval_fn(self.eval_steps)
209
+
210
+ if eval_outputs:
211
+ eval_outputs = tf.nest.map_structure(
212
+ lambda x: (x if isinstance(x, (float, bool)) else x.numpy()),
213
+ eval_outputs)
214
+
215
+ info = "step: {} evaluation metric: {}".format(
216
+ current_step, eval_outputs)
217
+ self._log_info(info)
218
+ self.last_eval_output = eval_outputs
219
+
220
+ self.eval_summary_manager.write_summaries(eval_outputs)
221
+ self.eval_summary_manager.flush()
222
+ if "continue_training" in eval_outputs.keys():
223
+ return eval_outputs["continue_training"]
224
+ else:
225
+ return True
226
+
227
+ def _maybe_save_checkpoints(self, current_step, force_trigger=False):
228
+ if self.checkpoint_manager.checkpoint_interval:
229
+ ckpt_path = self.checkpoint_manager.save(
230
+ checkpoint_number=current_step, check_interval=not force_trigger)
231
+ if ckpt_path is not None:
232
+ logging.info("Saved checkpoins in %s", ckpt_path)
233
+
234
+ def _maybe_evaluate(self, current_step, force_trigger=False):
235
+ if self.eval_trigger(current_step, force_trigger):
236
+ return self._evaluate_once(current_step)
237
+ return True
238
+
239
+ def _log_info(self, message):
240
+ """Logs `message` to the `info` log, and also prints to stdout."""
241
+ logging.info(message)
242
+ print(message)
243
+
244
+ def train(self, evaluate=True, num_acc_steps:int=1, manifest_path=None):
245
+ """Runs the training, with optional evaluation.
246
+
247
+ This handles evaluation, gathering summaries, and saving checkpoints.
248
+
249
+ Args:
250
+ evaluate: A boolean indicates whether to perform evaluation during
251
+ training.
252
+ num_acc_steps: Number of gradient accumulation steps.
253
+
254
+ Raises:
255
+ RuntimeError: If `global_step` is not updated correctly in `train_fn`.
256
+ """
257
+ if self.train_fn is None:
258
+ raise ValueError("`self.train_fn` is required when calling `train` "
259
+ "method.")
260
+ if self.global_step is None:
261
+ raise ValueError("`self.global_step` is required when calling `train` "
262
+ "method.")
263
+ if evaluate and self.eval_fn is None:
264
+ raise ValueError("`self.eval_fn` is required when calling `train` method "
265
+ "with `evaluate=True`")
266
+
267
+ step_timer = _StepTimer(self.global_step)
268
+ current_step = self.global_step.numpy()
269
+ logging.info("Train at step %s of %s", current_step, self.train_steps)
270
+ while current_step < self.train_steps:
271
+ # Calculates steps to run for the next train loop.
272
+ steps_per_loop = min(self.train_steps - current_step, self.steps_per_loop)
273
+ logging.info("Entering training loop with %s steps, at step %s of %s",
274
+ steps_per_loop, current_step, self.train_steps)
275
+ current_step += steps_per_loop
276
+ steps_per_loop = tf.convert_to_tensor(steps_per_loop, dtype=tf.int32)
277
+
278
+ with self.summary_manager.summary_writer.as_default():
279
+ train_outputs = self.train_fn(steps_per_loop, num_acc_steps, manifest_path)
280
+
281
+ # Updates and verifies the current step after a training loop finishes.
282
+ if current_step != self.global_step.numpy():
283
+ raise RuntimeError("`self.train_fn` is not updating `global_step` "
284
+ "correctly, expected: %s, actual: %s" %
285
+ (current_step, self.global_step.numpy()))
286
+
287
+ # Print information like metrics and steps_per_second after a training
288
+ # loop.
289
+ if train_outputs:
290
+ train_outputs = tf.nest.map_structure(
291
+ lambda x: x.numpy(), train_outputs)
292
+ steps_per_second = step_timer.steps_per_second()
293
+ info = "step: {} steps_per_second: {:.2f} {}".format(
294
+ current_step, steps_per_second, train_outputs)
295
+ self._log_info(info)
296
+
297
+ train_outputs = train_outputs or {}
298
+ train_outputs["steps_per_second"] = steps_per_second
299
+ self.summary_manager.write_summaries(train_outputs)
300
+
301
+ self._maybe_save_checkpoints(current_step)
302
+
303
+ if evaluate:
304
+ continue_training = self._maybe_evaluate(current_step)
305
+ if not continue_training:
306
+ break
307
+
308
+ self.summary_manager.write_summaries(train_outputs, always_write=True)
309
+ self.summary_manager.flush()
310
+ self._maybe_save_checkpoints(current_step, force_trigger=True)
311
+
312
+ def evaluate(self, continuous=False, timeout_fn=None):
313
+ """Runs the evaluation.
314
+
315
+ Args:
316
+ continuous: If `True`, will continously monitor the checkpoint directory
317
+ to evaluate on the latest checkpoint. If `False`, will do the evaluation
318
+ once.
319
+ timeout_fn: Optional callable to call after a timeout. If the function
320
+ returns True, then it means that no new checkpoints will be generated
321
+ and the iterator will exit.
322
+
323
+ Raises:
324
+ ValueError: If no checkpoint found in `self.checkpoint_manager.directory`.
325
+ """
326
+ if self.eval_fn is None:
327
+ raise ValueError("`self.eval_fn` should not be None to call "
328
+ "`evaluate()` method.")
329
+
330
+ if not continuous and timeout_fn is not None:
331
+ raise ValueError("`timeout_fn` can be only passed when `continuous` is "
332
+ "True")
333
+
334
+ if continuous:
335
+ for checkpoint_path in tf.train.checkpoints_iterator(
336
+ self.checkpoint_manager.directory, timeout_fn=timeout_fn):
337
+ self._restore_model(checkpoint_path)
338
+ self._evaluate_once(self.global_step.numpy())
339
+ return
340
+
341
+ latest_checkpoint = self.checkpoint_manager.latest_checkpoint
342
+ if not latest_checkpoint:
343
+ raise ValueError("no checkpoint found in dir %s" %
344
+ self.checkpoint_manager.directory)
345
+ self._restore_model()
346
+ self._evaluate_once(self.global_step.numpy())
347
+
348
+ def warmup(self):
349
+ """Runs device warmup.
350
+
351
+ This handles running a training loop on dummy data to move TF function
352
+ compilation outside of the training loop.
353
+
354
+ """
355
+ if self.global_step is None:
356
+ raise ValueError("`self.global_step` is required when calling `warmup` "
357
+ "method.")
358
+
359
+ step_timer = _StepTimer(self.global_step)
360
+ current_step = self.global_step.numpy()
361
+ logging.info("Warmup at step %s of %s", current_step,
362
+ self.device_warmup_steps)
363
+ while current_step < self.device_warmup_steps:
364
+ # Calculates steps to run for the next train loop.
365
+ steps_per_loop = self.device_warmup_steps
366
+ logging.info("Entering warmup loop with %s steps, at step %s of %s",
367
+ steps_per_loop, current_step, self.device_warmup_steps)
368
+ current_step += steps_per_loop
369
+ steps_per_loop = tf.convert_to_tensor(steps_per_loop, dtype=tf.int32)
370
+
371
+ with self.summary_manager.summary_writer.as_default():
372
+ self.warmup_fn(steps_per_loop)
373
+
374
+ steps_per_second = step_timer.steps_per_second()
375
+ info = "step: {} steps_per_second: {:.2f}".format(
376
+ current_step, steps_per_second)
377
+ self._log_info(info)
378
+
379
+ class _StepTimer(object):
380
+ """Utility class for measuring steps/second."""
381
+
382
+ def __init__(self, step):
383
+ self.step = step
384
+ self.start()
385
+
386
+ def start(self):
387
+ self.last_iteration = self.step.numpy()
388
+ self.last_time = time.time()
389
+
390
+ def steps_per_second(self, restart=True):
391
+ value = ((self.step.numpy() - self.last_iteration) /
392
+ (time.time() - self.last_time))
393
+ if restart:
394
+ self.start()
395
+ return value
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/grad_utils.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """Some gradient util functions to help users writing custom training loop."""
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ # from __future__ import google_type_annotations
20
+ from __future__ import print_function
21
+
22
+ from absl import logging
23
+
24
+ import tensorflow.compat.v2 as tf
25
+
26
+
27
+ def _filter_grads(grads_and_vars):
28
+ """Filter out iterable with grad equal to None."""
29
+ grads_and_vars = tuple(grads_and_vars)
30
+ if not grads_and_vars:
31
+ return grads_and_vars
32
+ filtered = []
33
+ vars_with_empty_grads = []
34
+ for grad, var in grads_and_vars:
35
+ if grad is None:
36
+ vars_with_empty_grads.append(var)
37
+ else:
38
+ filtered.append((grad, var))
39
+ filtered = tuple(filtered)
40
+ if not filtered:
41
+ raise ValueError("No gradients provided for any variable: %s." %
42
+ ([v.name for _, v in grads_and_vars],))
43
+ if vars_with_empty_grads:
44
+ logging.warning(
45
+ ("Gradients do not exist for variables %s when minimizing the loss."),
46
+ ([v.name for v in vars_with_empty_grads]))
47
+ return filtered
48
+
49
+
50
+ def _filter_and_allreduce_gradients(grads_and_vars,
51
+ allreduce_precision="float32"):
52
+ """Filter None grads and then allreduce gradients in specified precision.
53
+
54
+ This utils function is used when users intent to explicitly allreduce
55
+ gradients and customize gradients operations before and after allreduce.
56
+ The allreduced gradients are then passed to optimizer.apply_gradients(
57
+ experimental_aggregate_gradients=False).
58
+
59
+ Arguments:
60
+ grads_and_vars: gradients and variables pairs.
61
+ allreduce_precision: Whether to allreduce gradients in float32 or float16.
62
+
63
+ Returns:
64
+ pairs of allreduced non-None gradients and variables.
65
+ """
66
+ filtered_grads_and_vars = _filter_grads(grads_and_vars)
67
+ (grads, variables) = zip(*filtered_grads_and_vars)
68
+ if allreduce_precision == "float16":
69
+ grads = [tf.cast(grad, "float16") for grad in grads]
70
+ allreduced_grads = tf.distribute.get_replica_context().all_reduce(
71
+ tf.distribute.ReduceOp.SUM, grads)
72
+ if allreduce_precision == "float16":
73
+ allreduced_grads = [tf.cast(grad, "float32") for grad in allreduced_grads]
74
+ return allreduced_grads, variables
75
+
76
+
77
+ def _run_callbacks(callbacks, grads_and_vars):
78
+ for callback in callbacks:
79
+ grads_and_vars = callback(grads_and_vars)
80
+ return grads_and_vars
81
+
82
+
83
+ def minimize_using_explicit_allreduce(tape,
84
+ optimizer,
85
+ loss,
86
+ trainable_variables,
87
+ pre_allreduce_callbacks=None,
88
+ post_allreduce_callbacks=None):
89
+ """Minimizes loss for one step by updating `trainable_variables`.
90
+
91
+ Minimizes loss for one step by updating `trainable_variables`.
92
+ This explicitly performs gradient allreduce, instead of relying on implicit
93
+ allreduce in optimizer.apply_gradients(). If training using FP16 mixed
94
+ precision, explicit allreduce will aggregate gradients in FP16 format.
95
+ For TPU and GPU training using FP32, explicit allreduce will aggregate
96
+ gradients in FP32 format.
97
+
98
+ Arguments:
99
+ tape: An instance of `tf.GradientTape`.
100
+ optimizer: An instance of `tf.keras.optimizers.Optimizer`.
101
+ loss: the loss tensor.
102
+ trainable_variables: A list of model Variables.
103
+ pre_allreduce_callbacks: A list of callback functions that takes gradients
104
+ and model variables pairs as input, manipulate them, and returns a new
105
+ gradients and model variables pairs. The callback functions will be
106
+ invoked in the list order and before gradients are allreduced.
107
+ With mixed precision training, the pre_allreduce_allbacks will be
108
+ applied on scaled_gradients. Default is no callbacks.
109
+ post_allreduce_callbacks: A list of callback functions that takes
110
+ gradients and model variables pairs as input, manipulate them, and
111
+ returns a new gradients and model variables paris. The callback
112
+ functions will be invoked in the list order and right before gradients
113
+ are applied to variables for updates. Default is no callbacks.
114
+ """
115
+ if isinstance(optimizer,
116
+ tf.keras.mixed_precision.LossScaleOptimizer):
117
+ # FP16 GPU code path
118
+ with tape:
119
+ scaled_loss = optimizer.get_scaled_loss(loss)
120
+ scaled_grads = tape.gradient(scaled_loss, trainable_variables)
121
+ grads_and_vars = zip(scaled_grads, trainable_variables)
122
+ if pre_allreduce_callbacks:
123
+ grads_and_vars = _run_callbacks(pre_allreduce_callbacks, grads_and_vars)
124
+ (allreduced_scaled_grads,
125
+ filtered_training_vars) = _filter_and_allreduce_gradients(
126
+ grads_and_vars, allreduce_precision="float16")
127
+ allreduced_unscaled_grads = optimizer.get_unscaled_gradients(
128
+ allreduced_scaled_grads)
129
+ grads_and_vars = zip(allreduced_unscaled_grads, filtered_training_vars)
130
+ else:
131
+ # TPU or FP32 GPU code path
132
+ grads = tape.gradient(loss, trainable_variables)
133
+ grads_and_vars = zip(grads, trainable_variables)
134
+ if pre_allreduce_callbacks:
135
+ grads_and_vars = _run_callbacks(pre_allreduce_callbacks, grads_and_vars)
136
+ (allreduced_grads,
137
+ filtered_training_vars) = _filter_and_allreduce_gradients(
138
+ grads_and_vars, allreduce_precision="float32")
139
+ grads_and_vars = zip(allreduced_grads, filtered_training_vars)
140
+ if post_allreduce_callbacks:
141
+ grads_and_vars = _run_callbacks(post_allreduce_callbacks, grads_and_vars)
142
+ optimizer.apply_gradients(
143
+ grads_and_vars, experimental_aggregate_gradients=False)
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/runnable.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """An abstraction that users can easily handle their custom training loops."""
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ # from __future__ import google_type_annotations
20
+ from __future__ import print_function
21
+
22
+ import abc
23
+ import six
24
+ import tensorflow.compat.v2 as tf
25
+ from typing import Dict, Optional, Text
26
+
27
+
28
+ @six.add_metaclass(abc.ABCMeta)
29
+ class AbstractTrainable(tf.Module):
30
+ """An abstract class defining the APIs required for training."""
31
+
32
+ @abc.abstractmethod
33
+ def train(self,
34
+ num_steps: Optional[tf.Tensor]) -> Optional[Dict[Text, tf.Tensor]]:
35
+ """Implements model training with multiple steps.
36
+
37
+ In training, it is common to break the total training steps into several
38
+ training loops, so users can do checkpointing, write summaries and run some
39
+ python callbacks. This is necessary for getting good performance in TPU
40
+ training, as the overhead for launching a multi worker tf.function may be
41
+ large in Eager mode. It is usually encouraged to create a host training loop
42
+ (e.g. using a `tf.range` wrapping `strategy.run` inside a
43
+ `tf.function`) in the TPU case. For the cases that don't require host
44
+ training loop to acheive peak performance, users can just implement a simple
45
+ python loop to drive each step.
46
+
47
+ Args:
48
+ num_steps: A guideline for how many training steps to run. Note that it is
49
+ up to the model what constitutes a "step" (this may involve more than
50
+ one update to model parameters, e.g. if training a GAN).
51
+
52
+ Returns:
53
+ The function may return a dictionary of `Tensors`, which will be
54
+ written to logs and as TensorBoard summaries.
55
+ """
56
+ pass
57
+
58
+
59
+ @six.add_metaclass(abc.ABCMeta)
60
+ class AbstractEvaluable(tf.Module):
61
+ """An abstract class defining the APIs required for evaluation."""
62
+
63
+ @abc.abstractmethod
64
+ def evaluate(
65
+ self, num_steps: Optional[tf.Tensor]) -> Optional[Dict[Text, tf.Tensor]]:
66
+ """Implements model evaluation.
67
+
68
+ Args:
69
+ num_steps: A guideline for how many evaluation steps to run. Note that it
70
+ is up to the model what constitutes a "step". Generally, it may be
71
+ desirable to support both a limited number of eval steps and iterating
72
+ over a full dataset (however many steps are required) when `num_steps`
73
+ is `None`.
74
+
75
+ Returns:
76
+ The function may return a dictionary of `Tensors`, which will be
77
+ written to logs and as TensorBoard summaries.
78
+ """
79
+ pass
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/standard_runnable.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """An abstraction that users can easily handle their custom training loops."""
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ # from __future__ import google_type_annotations
20
+ from __future__ import print_function
21
+
22
+ import abc
23
+ import six
24
+ import tensorflow.compat.v2 as tf
25
+ from typing import Dict, Optional, Text
26
+
27
+ from TensorFlow.common.training import runnable
28
+ from TensorFlow.common.training import utils
29
+
30
+
31
+ @six.add_metaclass(abc.ABCMeta)
32
+ class StandardTrainable(runnable.AbstractTrainable):
33
+ """Implements the standard functionality of AbstractTrainable APIs."""
34
+
35
+ def __init__(self, use_tf_while_loop=True, use_tf_function=True):
36
+ if use_tf_while_loop and not use_tf_function:
37
+ raise ValueError("`use_tf_while_loop=True` and `use_tf_function=False` "
38
+ "is not supported")
39
+ self.use_tf_while_loop = use_tf_while_loop
40
+ self.use_tf_function = use_tf_function
41
+ self.train_dataset = None
42
+ self.train_iter = None
43
+ self.train_loop_fn = None
44
+
45
+ @abc.abstractmethod
46
+ def build_train_dataset(self, manifest_path=None):
47
+ """Builds the training datasets.
48
+
49
+ Returns:
50
+ A tf.nest-compatible structure of tf.data.Dataset or DistributedDataset.
51
+ """
52
+ pass
53
+
54
+ def train(self, num_steps: Optional[tf.Tensor], num_acc_steps:int=1, manifest_path=None) -> Optional[Dict[Text, tf.Tensor]]:
55
+ """See base class."""
56
+ if self.train_dataset is None:
57
+ # Build train input dataset
58
+ self.train_dataset = self.build_train_dataset(manifest_path=manifest_path)
59
+ self.train_iter = tf.nest.map_structure(iter, self.train_dataset)
60
+
61
+ if self.train_loop_fn is None:
62
+ train_fn = self.train_step
63
+ if self.use_tf_while_loop:
64
+ self.train_loop_fn = utils.create_tf_while_loop_fn(train_fn)
65
+ else:
66
+ if self.use_tf_function:
67
+ train_fn = tf.function(train_fn)
68
+ self.train_loop_fn = utils.create_loop_fn(train_fn)
69
+
70
+ self.train_loop_begin()
71
+ self.train_loop_fn(self.train_iter, num_steps, num_acc_steps)
72
+ return self.train_loop_end()
73
+
74
+ def train_loop_begin(self):
75
+ """Called once at the beginning of the training loop.
76
+
77
+ This is a good place to reset metrics that accumulate values over multiple
78
+ steps of training.
79
+ """
80
+ pass
81
+
82
+ @abc.abstractmethod
83
+ def train_step(self, iterator):
84
+ """Implements one step of training.
85
+
86
+ What a "step" consists of is up to the implementer. If using distribution
87
+ strategies, the call to this method should take place in the "cross-replica
88
+ context" for generality, to allow e.g. multiple iterator dequeues and calls
89
+ to `strategy.run`.
90
+
91
+ Args:
92
+ iterator: A tf.nest-compatible structure of tf.data Iterator or
93
+ DistributedIterator.
94
+ """
95
+ pass
96
+
97
+ def train_loop_end(self) -> Optional[Dict[Text, tf.Tensor]]:
98
+ """Called at the end of the training loop.
99
+
100
+ This is a good place to get metric results. The value returned from this
101
+ function will be returned as-is from the train() method.
102
+
103
+ Returns:
104
+ The function may return a dictionary of `Tensors`, which will be
105
+ written to logs and as TensorBoard summaries.
106
+ """
107
+ pass
108
+
109
+
110
+ @six.add_metaclass(abc.ABCMeta)
111
+ class StandardEvaluable(runnable.AbstractEvaluable):
112
+ """Implements the standard functionality of AbstractEvaluable APIs."""
113
+
114
+ def __init__(self, use_tf_function=True):
115
+ self.eval_use_tf_function = use_tf_function
116
+ self.eval_dataset = None
117
+ self.eval_loop_fn = None
118
+
119
+ @abc.abstractmethod
120
+ def build_eval_dataset(self):
121
+ """Builds the evaluation datasets.
122
+
123
+ Returns:
124
+ A tf.nest-compatible structure of tf.data.Dataset or DistributedDataset.
125
+ """
126
+ pass
127
+
128
+ def evaluate(
129
+ self, num_steps: Optional[tf.Tensor]) -> Optional[Dict[Text, tf.Tensor]]:
130
+ """See base class."""
131
+ if self.eval_dataset is None:
132
+ # Build train input dataset
133
+ self.eval_dataset = self.build_eval_dataset()
134
+
135
+ if self.eval_loop_fn is None:
136
+ eval_fn = self.eval_step
137
+ if self.eval_use_tf_function:
138
+ eval_fn = tf.function(eval_fn)
139
+ self.eval_loop_fn = utils.create_loop_fn(eval_fn)
140
+
141
+ # TODO(b/147718615): When async RPC is enabled in eager runtime, we make
142
+ # eval iterator as a class member so it doesn't get destroyed when out of
143
+ # the function scope.
144
+ self.eval_iter = tf.nest.map_structure(iter, self.eval_dataset)
145
+
146
+ self.eval_begin()
147
+ self.eval_loop_fn(self.eval_iter, num_steps)
148
+ return self.eval_end()
149
+
150
+ def eval_begin(self):
151
+ """Called once at the beginning of the evaluation.
152
+
153
+ This is a good place to reset metrics that accumulate values over the entire
154
+ evaluation.
155
+ """
156
+ pass
157
+
158
+ @abc.abstractmethod
159
+ def eval_step(self, iterator):
160
+ """Implements one step of evaluation.
161
+
162
+ What a "step" consists of is up to the implementer. If using distribution
163
+ strategies, the call to this method should take place in the "cross-replica
164
+ context" for generality, to allow e.g. multiple iterator dequeues and calls
165
+ to `strategy.run`.
166
+
167
+ Args:
168
+ iterator: A tf.nest-compatible structure of tf.data Iterator or
169
+ DistributedIterator.
170
+ """
171
+ pass
172
+
173
+ def eval_end(self) -> Optional[Dict[Text, tf.Tensor]]:
174
+ """Called at the end of the evaluation.
175
+
176
+ This is a good place to get metric results. The value returned from this
177
+ function will be returned as-is from the evaluate() method.
178
+
179
+ Returns:
180
+ The function may return a dictionary of `Tensors`, which will be
181
+ written to logs and as TensorBoard summaries.
182
+ """
183
+ pass
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/common/training/utils.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """Some layered modules/functions to help users writing custom training loop."""
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ # from __future__ import google_type_annotations
20
+ from __future__ import print_function
21
+
22
+ import abc
23
+ import inspect
24
+ import six
25
+
26
+ import tensorflow.compat.v2 as tf
27
+
28
+
29
+ def create_loop_fn(step_fn):
30
+ """Creates a multiple steps function driven by the python while loop.
31
+
32
+ Args:
33
+ step_fn: A function which takes `iterator` as input.
34
+
35
+ Returns:
36
+ A callable defined as the `loop_fn` defination below.
37
+ """
38
+
39
+ def loop_fn(iterator, num_steps, state=None, reduce_fn=None):
40
+ """A loop function with multiple steps.
41
+
42
+ Args:
43
+ iterator: A nested structure of tf.data `Iterator` or
44
+ `DistributedIterator`.
45
+ num_steps: The number of steps in the loop. If `num_steps==-1`, will
46
+ iterate until exausting the iterator.
47
+ state: An optional initial state before running the loop.
48
+ reduce_fn: a callable defined as `def reduce_fn(state, value)`, where
49
+ `value` is the outputs from `step_fn`.
50
+
51
+ Returns:
52
+ The updated state.
53
+ """
54
+ try:
55
+ step = 0
56
+ # To make sure the OutOfRangeError exception can be handled well with
57
+ # async remote eager, we need to wrap the loop body in a `async_scope`.
58
+ with tf.experimental.async_scope():
59
+ while (num_steps == -1 or step < num_steps):
60
+ outputs = step_fn(iterator)
61
+ if reduce_fn is not None:
62
+ state = reduce_fn(state, outputs)
63
+ step += 1
64
+ return state
65
+ except (StopIteration, tf.errors.OutOfRangeError):
66
+ tf.experimental.async_clear_error()
67
+ return state
68
+
69
+ return loop_fn
70
+
71
+
72
+ def create_tf_while_loop_fn(step_fn):
73
+ """Create a multiple steps function driven by tf.while_loop on the host.
74
+
75
+ Args:
76
+ step_fn: A function which takes `iterator` as input.
77
+
78
+ Returns:
79
+ A callable defined as the `loop_fn` defination below.
80
+ """
81
+
82
+ @tf.function
83
+ def loop_fn(iterator, num_steps, num_acc_steps:int=1):
84
+ """A loop function with multiple steps.
85
+
86
+ Args:
87
+ iterator: A nested structure of tf.data `Iterator` or
88
+ `DistributedIterator`.
89
+ num_steps: The number of steps in the loop. Must be a tf.Tensor.
90
+ num_acc_steps: Number of gradient accumulation steps.
91
+ """
92
+ if not isinstance(num_steps, tf.Tensor):
93
+ raise ValueError("`num_steps` should be an `tf.Tensor`. Python object "
94
+ "may cause retracing.")
95
+
96
+ for _ in tf.range(num_steps):
97
+ for _ in range(num_acc_steps):
98
+ step_fn(iterator)
99
+
100
+ return loop_fn
101
+
102
+
103
+ def make_distributed_dataset(strategy, dataset_or_fn, *args, **kwargs):
104
+ """A helper function to create distributed dataset.
105
+
106
+ Args:
107
+ strategy: An instance of `tf.distribute.Strategy`.
108
+ dataset_or_fn: A instance of `tf.data.Dataset` or a function which takes an
109
+ `tf.distribute.InputContext` as input and returns a `tf.data.Dataset`. If
110
+ it is a function, it could optionally have an argument named
111
+ `input_context` which is `tf.distribute.InputContext` argument type.
112
+ *args: The list of arguments to be passed to dataset_or_fn.
113
+ **kwargs: Any keyword arguments to be passed.
114
+
115
+ Returns:
116
+ A distributed Dataset.
117
+ """
118
+ if strategy is None:
119
+ strategy = tf.distribute.get_strategy()
120
+
121
+ if isinstance(dataset_or_fn, tf.data.Dataset):
122
+ return strategy.experimental_distribute_dataset(dataset_or_fn)
123
+
124
+ if not callable(dataset_or_fn):
125
+ raise ValueError("`dataset_or_fn` should be either callable or an instance "
126
+ "of `tf.data.Dataset`")
127
+
128
+ def dataset_fn(ctx):
129
+ """Wrapped dataset function for creating distributed dataset.."""
130
+
131
+ # If `dataset_or_fn` is a function and has `input_context` as argument
132
+ # names, pass `ctx` as the value of `input_context` when calling
133
+ # `dataset_or_fn`. Otherwise `ctx` will not be used when calling
134
+ # `dataset_or_fn`.
135
+ if six.PY3:
136
+ argspec = inspect.getfullargspec(dataset_or_fn)
137
+ else:
138
+ argspec = inspect.getargspec(dataset_or_fn)
139
+ args_names = argspec.args
140
+
141
+ if "input_context" in args_names:
142
+ kwargs["input_context"] = ctx
143
+ ds = dataset_or_fn(*args, **kwargs)
144
+ return ds
145
+
146
+ return strategy.experimental_distribute_datasets_from_function(dataset_fn)
147
+
148
+
149
+ class SummaryManager(object):
150
+ """A class manages writing summaries."""
151
+
152
+ def __init__(self,
153
+ summary_writer,
154
+ summary_fn,
155
+ global_step=None,
156
+ summary_interval=None):
157
+ """Construct a summary manager object.
158
+
159
+ Args:
160
+ summary_writer: A `tf.summary.SummaryWriter` instance for writing
161
+ summaries.
162
+ summary_fn: A callable defined as `def summary_fn(name, tensor,
163
+ step=None)`, which describes the summary operation.
164
+ global_step: A `tf.Variable` instance for checking the current global step
165
+ value, in case users want to save summaries every N steps.
166
+ summary_interval: An integer, indicates the minimum step interval between
167
+ two summaries.
168
+ """
169
+ if summary_writer is not None:
170
+ self._summary_writer = summary_writer
171
+ self._enabled = True
172
+ else:
173
+ self._summary_writer = tf.summary.create_noop_writer()
174
+ self._enabled = False
175
+ self._summary_fn = summary_fn
176
+
177
+ if global_step is None:
178
+ self._global_step = tf.summary.experimental.get_step()
179
+ else:
180
+ self._global_step = global_step
181
+
182
+ if summary_interval is not None:
183
+ if self._global_step is None:
184
+ raise ValueError("`summary_interval` is not None, but no `global_step` "
185
+ "can be obtained ")
186
+ self._last_summary_step = self._global_step.numpy()
187
+ self._summary_interval = summary_interval
188
+
189
+ @property
190
+ def summary_interval(self):
191
+ return self._summary_interval
192
+
193
+ @property
194
+ def summary_writer(self):
195
+ """Returns the underlying summary writer."""
196
+ return self._summary_writer
197
+
198
+ def flush(self):
199
+ """Flush the underlying summary writer."""
200
+ if self._enabled:
201
+ tf.summary.flush(self._summary_writer)
202
+
203
+ def write_summaries(self, items, always_write=True):
204
+ """Write a bulk of summaries.
205
+
206
+ Args:
207
+ items: a dictionary of `Tensors` for writing summaries.
208
+ always_write: An optional boolean. If `True`, the manager will always
209
+ write summaries unless the summaries have been written for the same
210
+ step. Otherwise the manager will only write the summaries if the
211
+ interval between summaries are larger than `summary_interval`.
212
+
213
+ Returns:
214
+ A boolean indicates whether the summaries are written or not.
215
+ """
216
+ # TODO(rxsang): Support writing summaries with nested structure, so users
217
+ # can split the summaries into different directories for nicer visualization
218
+ # in Tensorboard, like train and eval metrics.
219
+ if not self._enabled:
220
+ return False
221
+
222
+ if self._summary_interval is not None:
223
+ current_step = self._global_step.numpy()
224
+ if current_step == self._last_summary_step:
225
+ return False
226
+ if not always_write and current_step < (self._last_summary_step +
227
+ self._summary_interval):
228
+ return False
229
+ self._last_summary_step = current_step
230
+
231
+ with self._summary_writer.as_default():
232
+ for name, tensor in items.items():
233
+ self._summary_fn(name, tensor, step=self._global_step)
234
+ return True
235
+
236
+
237
+ @six.add_metaclass(abc.ABCMeta)
238
+ class Trigger(object):
239
+ """An abstract class representing a "trigger" for some event."""
240
+
241
+ @abc.abstractmethod
242
+ def __call__(self, value: float, force_trigger=False):
243
+ """Maybe trigger the event based on the given value.
244
+
245
+ Args:
246
+ value: the value for triggering.
247
+ force_trigger: Whether the trigger is forced triggered.
248
+
249
+ Returns:
250
+ `True` if the trigger is triggered on the given `value`, and
251
+ `False` otherwise.
252
+ """
253
+
254
+ @abc.abstractmethod
255
+ def reset(self):
256
+ """Reset states in the trigger."""
257
+
258
+
259
+ class IntervalTrigger(Trigger):
260
+ """Triggers on every fixed interval."""
261
+
262
+ def __init__(self, interval, start=0):
263
+ """Constructs the IntervalTrigger.
264
+
265
+ Args:
266
+ interval: The triggering interval.
267
+ start: An initial value for the trigger.
268
+ """
269
+ self._interval = interval
270
+ self._last_trigger_value = start
271
+
272
+ def __call__(self, value, force_trigger=False):
273
+ """Maybe trigger the event based on the given value.
274
+
275
+ Args:
276
+ value: the value for triggering.
277
+ force_trigger: If True, the trigger will be forced triggered unless the
278
+ last trigger value is equal to `value`.
279
+
280
+ Returns:
281
+ `True` if the trigger is triggered on the given `value`, and
282
+ `False` otherwise.
283
+ """
284
+ if force_trigger and value != self._last_trigger_value:
285
+ self._last_trigger_value = value
286
+ return True
287
+
288
+ if self._interval and self._interval > 0:
289
+ if value >= self._last_trigger_value + self._interval:
290
+ self._last_trigger_value = value
291
+ return True
292
+ return False
293
+
294
+ def reset(self):
295
+ """See base class."""
296
+ self._last_trigger_value = 0
297
+
298
+
299
+ class EpochHelper(object):
300
+ """A Helper class to handle epochs in Customized Training Loop."""
301
+
302
+ def __init__(self, epoch_steps, global_step):
303
+ """Constructs the EpochHelper.
304
+
305
+ Args:
306
+ epoch_steps: An integer indicates how many steps in an epoch.
307
+ global_step: A `tf.Variable` instance indicates the current global step.
308
+ """
309
+ self._epoch_steps = epoch_steps
310
+ self._global_step = global_step
311
+ self._current_epoch = None
312
+ self._epoch_start_step = None
313
+ self._in_epoch = False
314
+
315
+ def epoch_begin(self):
316
+ """Returns whether a new epoch should begin."""
317
+ if self._in_epoch:
318
+ return False
319
+ current_step = self._global_step.numpy()
320
+ self._epoch_start_step = current_step
321
+ self._current_epoch = current_step // self._epoch_steps
322
+ self._in_epoch = True
323
+ return True
324
+
325
+ def epoch_end(self):
326
+ """Returns whether the current epoch should end."""
327
+ if not self._in_epoch:
328
+ raise ValueError("`epoch_end` can only be called inside an epoch")
329
+ current_step = self._global_step.numpy()
330
+ epoch = current_step // self._epoch_steps
331
+
332
+ if epoch > self._current_epoch:
333
+ self._in_epoch = False
334
+ return True
335
+ return False
336
+
337
+ @property
338
+ def batch_index(self):
339
+ """Index of the next batch within the current epoch."""
340
+ return self._global_step.numpy() - self._epoch_start_step
341
+
342
+ @property
343
+ def current_epoch(self):
344
+ return self._current_epoch
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/__init__.py ADDED
File without changes
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/common.py ADDED
@@ -0,0 +1,523 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ # List of changes:
16
+ # - added Habana specific flags
17
+ # - added helper function for prefetching
18
+
19
+ # Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company
20
+
21
+ """Common util functions and classes used by both keras cifar and imagenet."""
22
+ from __future__ import absolute_import
23
+ from __future__ import division
24
+ from __future__ import print_function
25
+
26
+ import os
27
+
28
+ from absl import flags
29
+ import tensorflow as tf
30
+
31
+ import tensorflow_model_optimization as tfmot
32
+ from TensorFlow.utils.flags import core as flags_core
33
+ from TensorFlow.utils.misc import keras_utils
34
+ from TensorFlow.utils.flags._conventions import help_wrap
35
+ from habana_frameworks.tensorflow.multinode_helpers import comm_size
36
+ from TensorFlow.common.tb_utils import (
37
+ ExamplesPerSecondKerasHook, TensorBoardWithHParamsV1)
38
+
39
+ from TensorFlow.computer_vision.common import imagenet_preprocessing
40
+ from TensorFlow.computer_vision.Resnets.utils.optimizers.keras import lars_optimizer
41
+ from TensorFlow.computer_vision.Resnets.utils.optimizers.keras import lars_util
42
+
43
+ try:
44
+ import horovod.tensorflow as hvd
45
+ except ImportError:
46
+ hvd = None
47
+
48
+ FLAGS = flags.FLAGS
49
+ BASE_LEARNING_RATE = 0.1 # This matches Jing's version.
50
+ TRAIN_TOP_1 = 'training_accuracy_top_1'
51
+ LR_SCHEDULE = [ # (multiplier, epoch to start) tuples
52
+ (1.0, 5), (0.1, 30), (0.01, 60), (0.001, 80)
53
+ ]
54
+
55
+ global_batch_size = None
56
+ def get_global_batch_size(batch_size, num_acc_steps:int=1):
57
+ global global_batch_size
58
+ if global_batch_size is None:
59
+ global_batch_size = batch_size
60
+ if hvd is not None and hvd.is_initialized():
61
+ global_batch_size = batch_size * comm_size()
62
+ global_batch_size = global_batch_size * num_acc_steps
63
+ return global_batch_size
64
+
65
+ class PiecewiseConstantDecayWithWarmup(
66
+ tf.keras.optimizers.schedules.LearningRateSchedule):
67
+ """Piecewise constant decay with warmup schedule."""
68
+
69
+ def __init__(self, batch_size, epoch_size, warmup_epochs, boundaries,
70
+ multipliers, compute_lr_on_cpu=False, name=None):
71
+ super(PiecewiseConstantDecayWithWarmup, self).__init__()
72
+ if len(boundaries) != len(multipliers) - 1:
73
+ raise ValueError('The length of boundaries must be 1 less than the '
74
+ 'length of multipliers')
75
+
76
+ base_lr_batch_size = 256
77
+ steps_per_epoch = epoch_size // batch_size
78
+
79
+ self.rescaled_lr = BASE_LEARNING_RATE * batch_size / base_lr_batch_size
80
+ self.step_boundaries = [float(steps_per_epoch) * x for x in boundaries]
81
+ self.lr_values = [self.rescaled_lr * m for m in multipliers]
82
+ self.warmup_steps = warmup_epochs * steps_per_epoch
83
+ self.compute_lr_on_cpu = compute_lr_on_cpu
84
+ self.name = name
85
+
86
+ self.learning_rate_ops_cache = {}
87
+
88
+ def __call__(self, step):
89
+ if tf.executing_eagerly():
90
+ return self._get_learning_rate(step)
91
+
92
+ # In an eager function or graph, the current implementation of optimizer
93
+ # repeatedly call and thus create ops for the learning rate schedule. To
94
+ # avoid this, we cache the ops if not executing eagerly.
95
+ graph = tf.compat.v1.get_default_graph()
96
+ if graph not in self.learning_rate_ops_cache:
97
+ if self.compute_lr_on_cpu:
98
+ with tf.device('/device:CPU:0'):
99
+ self.learning_rate_ops_cache[graph] = self._get_learning_rate(step)
100
+ else:
101
+ self.learning_rate_ops_cache[graph] = self._get_learning_rate(step)
102
+ return self.learning_rate_ops_cache[graph]
103
+
104
+ def _get_learning_rate(self, step):
105
+ """Compute learning rate at given step."""
106
+ with tf.compat.v1.name_scope(self.name, 'PiecewiseConstantDecayWithWarmup',
107
+ [self.rescaled_lr, self.step_boundaries,
108
+ self.lr_values, self.warmup_steps,
109
+ self.compute_lr_on_cpu]):
110
+ def warmup_lr(step):
111
+ return self.rescaled_lr * (
112
+ tf.cast(step, tf.float32) / tf.cast(self.warmup_steps, tf.float32))
113
+ def piecewise_lr(step):
114
+ return tf.compat.v1.train.piecewise_constant(
115
+ step, self.step_boundaries, self.lr_values)
116
+ return tf.cond(step < self.warmup_steps,
117
+ lambda: warmup_lr(step),
118
+ lambda: piecewise_lr(step))
119
+
120
+ def get_config(self):
121
+ return {
122
+ 'rescaled_lr': self.rescaled_lr,
123
+ 'step_boundaries': self.step_boundaries,
124
+ 'lr_values': self.lr_values,
125
+ 'warmup_steps': self.warmup_steps,
126
+ 'compute_lr_on_cpu': self.compute_lr_on_cpu,
127
+ 'name': self.name
128
+ }
129
+
130
+
131
+ def get_lr_schedule(flags_obj, global_batch_size, train_steps,mlperf_mlloger,mlperf_mllog):
132
+ lr_schedule = None
133
+
134
+ if flags_obj.lr_schedule == 'polynomial':
135
+ lr_schedule = lars_util.PolynomialDecayWithWarmup(
136
+ batch_size=global_batch_size,
137
+ steps_per_epoch=imagenet_preprocessing.NUM_IMAGES['train'] // global_batch_size,
138
+ train_steps=train_steps,
139
+ initial_learning_rate=flags_obj.base_learning_rate,
140
+ end_learning_rate=flags_obj.end_learning_rate,
141
+ warmup_epochs=flags_obj.warmup_epochs,
142
+ mlperf_mlloger=mlperf_mlloger,
143
+ mlperf_mllog=mlperf_mllog)
144
+ elif flags_obj.lr_schedule == 'piecewise':
145
+ lr_schedule = PiecewiseConstantDecayWithWarmup(
146
+ batch_size=global_batch_size,
147
+ epoch_size=imagenet_preprocessing.NUM_IMAGES['train'],
148
+ warmup_epochs=LR_SCHEDULE[0][1],
149
+ boundaries=list(p[1] for p in LR_SCHEDULE[1:]),
150
+ multipliers=list(p[0] for p in LR_SCHEDULE),
151
+ compute_lr_on_cpu=False)
152
+ elif flags_obj.lr_schedule == 'constant':
153
+ lr_schedule = flags_obj.base_learning_rate * global_batch_size / 256
154
+ else:
155
+ raise ValueError('lr_schedule "%s" is unknown.' % flags_obj.lr_schedule)
156
+
157
+ return lr_schedule
158
+
159
+
160
+ def get_optimizer(flags_obj, global_batch_size, train_steps,mlperf_mlloger,mlperf_mllog):
161
+ optimizer = None
162
+ lr_schedule = get_lr_schedule(flags_obj, global_batch_size, train_steps,mlperf_mlloger,mlperf_mllog)
163
+
164
+ if flags_obj.optimizer == 'SGD':
165
+ # The learning_rate is overwritten at the beginning of each step by callback.
166
+ optimizer = tf.keras.optimizers.legacy.SGD(learning_rate=lr_schedule, momentum=0.9)
167
+
168
+ elif flags_obj.optimizer == 'LARS':
169
+ optimizer = lars_optimizer.LARSOptimizer(
170
+ learning_rate=lr_schedule,
171
+ momentum=flags_obj.momentum,
172
+ weight_decay=flags_obj.weight_decay,
173
+ skip_list=['batch_normalization', 'bias', 'bn'],
174
+ epsilon=flags_obj.lars_epsilon)
175
+ else:
176
+ raise ValueError('optimizer "%s" is unknown.' % flags_obj.optimizer)
177
+
178
+ return optimizer
179
+
180
+
181
+ def get_callbacks(
182
+ steps_per_epoch,
183
+ pruning_method=None,
184
+ enable_checkpoint_and_export=False,
185
+ model_dir=None):
186
+ """Returns common callbacks."""
187
+ time_callback = keras_utils.TimeHistory(
188
+ FLAGS.batch_size,
189
+ FLAGS.log_steps,
190
+ logdir=FLAGS.model_dir if FLAGS.enable_tensorboard else None)
191
+ callbacks = [time_callback]
192
+
193
+ if FLAGS.enable_tensorboard:
194
+ callbacks += [
195
+ TensorBoardWithHParamsV1(
196
+ FLAGS.flag_values_dict(),
197
+ log_dir=FLAGS.model_dir,
198
+ update_freq=FLAGS.log_steps),
199
+ ExamplesPerSecondKerasHook(
200
+ output_dir=FLAGS.model_dir,
201
+ every_n_steps=FLAGS.log_steps)
202
+ ]
203
+
204
+ if FLAGS.profile_steps:
205
+ profiler_callback = keras_utils.get_profiler_callback(
206
+ FLAGS.model_dir,
207
+ FLAGS.profile_steps,
208
+ FLAGS.enable_tensorboard,
209
+ steps_per_epoch)
210
+ callbacks.append(profiler_callback)
211
+
212
+ is_pruning_enabled = pruning_method is not None
213
+
214
+ if is_pruning_enabled:
215
+ callbacks.append(tfmot.sparsity.keras.UpdatePruningStep())
216
+ if model_dir is not None:
217
+ callbacks.append(tfmot.sparsity.keras.PruningSummaries(
218
+ log_dir=model_dir, profile_batch=0))
219
+
220
+ if enable_checkpoint_and_export:
221
+ if model_dir is not None:
222
+ ckpt_full_path = os.path.join(model_dir, 'model.ckpt-{epoch:04d}')
223
+ callbacks.append(
224
+ tf.keras.callbacks.ModelCheckpoint(ckpt_full_path,
225
+ save_weights_only=True))
226
+ return callbacks
227
+
228
+
229
+ def build_stats(history, eval_output, callbacks):
230
+ """Normalizes and returns dictionary of stats.
231
+
232
+ Args:
233
+ history: Results of the training step. Supports both categorical_accuracy
234
+ and sparse_categorical_accuracy.
235
+ eval_output: Output of the eval step. Assumes first value is eval_loss and
236
+ second value is accuracy_top_1.
237
+ callbacks: a list of callbacks which might include a time history callback
238
+ used during keras.fit.
239
+
240
+ Returns:
241
+ Dictionary of normalized results.
242
+ """
243
+ stats = {}
244
+ if eval_output:
245
+ stats['accuracy_top_1'] = float(eval_output[1])
246
+ stats['eval_loss'] = float(eval_output[0])
247
+ if history and history.history:
248
+ train_hist = history.history
249
+ # Gets final loss from training.
250
+ stats['loss'] = float(train_hist['loss'][-1])
251
+ # Gets top_1 training accuracy.
252
+ if 'categorical_accuracy' in train_hist:
253
+ stats[TRAIN_TOP_1] = float(train_hist['categorical_accuracy'][-1])
254
+ elif 'sparse_categorical_accuracy' in train_hist:
255
+ stats[TRAIN_TOP_1] = float(train_hist['sparse_categorical_accuracy'][-1])
256
+ elif 'accuracy' in train_hist:
257
+ stats[TRAIN_TOP_1] = float(train_hist['accuracy'][-1])
258
+
259
+ if not callbacks:
260
+ return stats
261
+
262
+ # Look for the time history callback which was used during keras.fit
263
+ for callback in callbacks:
264
+ if isinstance(callback, keras_utils.TimeHistory):
265
+ timestamp_log = callback.timestamp_log
266
+ stats['step_timestamp_log'] = timestamp_log
267
+ stats['train_finish_time'] = callback.train_finish_time
268
+ if callback.epoch_runtime_log:
269
+ stats['avg_exp_per_second'] = callback.average_examples_per_second
270
+
271
+ return stats
272
+
273
+
274
+ def define_keras_flags(
275
+ dynamic_loss_scale=True,
276
+ model=False,
277
+ optimizer=False,
278
+ pretrained_filepath=False):
279
+ """Define flags for Keras models."""
280
+ flags_core.define_base(clean=True, num_gpu=True, run_eagerly=True,
281
+ train_epochs=True, epochs_between_evals=True,
282
+ distribution_strategy=True)
283
+ flags_core.define_performance(num_parallel_calls=False,
284
+ synthetic_data=True,
285
+ dtype=True,
286
+ all_reduce_alg=True,
287
+ num_packs=True,
288
+ tf_gpu_thread_mode=True,
289
+ datasets_num_private_threads=True,
290
+ dynamic_loss_scale=dynamic_loss_scale,
291
+ loss_scale=True,
292
+ fp16_implementation=True,
293
+ tf_data_experimental_slack=True,
294
+ enable_xla=True,
295
+ dataset_cache=True)
296
+ flags_core.define_image()
297
+ flags_core.define_benchmark()
298
+ flags_core.define_distribution()
299
+ flags.adopt_module_key_flags(flags_core)
300
+
301
+ flags.DEFINE_boolean(name='enable_eager', default=False, help='Enable eager?')
302
+ flags.DEFINE_boolean(name='skip_eval', default=False, help='Skip evaluation?')
303
+ # TODO(b/135607288): Remove this flag once we understand the root cause of
304
+ # slowdown when setting the learning phase in Keras backend.
305
+ flags.DEFINE_boolean(
306
+ name='set_learning_phase_to_train', default=True,
307
+ help='If skip eval, also set Keras learning phase to 1 (training).')
308
+ flags.DEFINE_boolean(
309
+ name='explicit_gpu_placement', default=False,
310
+ help='If not using distribution strategy, explicitly set device scope '
311
+ 'for the Keras training loop.')
312
+ flags.DEFINE_boolean(name='use_trivial_model', default=False,
313
+ help='Whether to use a trivial Keras model.')
314
+ flags.DEFINE_boolean(name='report_accuracy_metrics', default=True,
315
+ help='Report metrics during training and evaluation.')
316
+ flags.DEFINE_boolean(name='use_tensor_lr', default=True,
317
+ help='Use learning rate tensor instead of a callback.')
318
+ flags.DEFINE_string(
319
+ name='lr_schedule',
320
+ default='piecewise',
321
+ help='learning rate schedule. '
322
+ '"piecewise" for PiecewiseConstantDecayWithWarmup, '
323
+ '"polynomial" for PolynomialDecayWithWarmup, '
324
+ 'and "constant" for static learning rate.')
325
+ flags.DEFINE_boolean(
326
+ name='enable_tensorboard', default=False,
327
+ help='Whether to enable Tensorboard callback.')
328
+ flags.DEFINE_integer(
329
+ name='train_steps', default=None,
330
+ help='The number of steps to run for training. If it is larger than '
331
+ '# batches per epoch, then use # batches per epoch. This flag will be '
332
+ 'ignored if train_epochs is set to be larger than 1. ')
333
+ flags.DEFINE_string(
334
+ name='profile_steps', default=None,
335
+ help='Save profiling data to model dir at given range of global steps. The '
336
+ 'value must be a comma separated pair of positive integers, specifying '
337
+ 'the first and last step to profile. For example, "--profile_steps=2,4" '
338
+ 'triggers the profiler to process 3 steps, starting from the 2nd step. '
339
+ 'Note that profiler has a non-trivial performance overhead, and the '
340
+ 'output file can be gigantic if profiling many steps.')
341
+ flags.DEFINE_boolean(
342
+ name='batchnorm_spatial_persistent', default=True,
343
+ help='Enable the spacial persistent mode for CuDNN batch norm kernel.')
344
+ flags.DEFINE_boolean(
345
+ name='enable_get_next_as_optional', default=False,
346
+ help='Enable get_next_as_optional behavior in DistributedIterator.')
347
+ flags.DEFINE_boolean(
348
+ name='enable_checkpoint_and_export', default=False,
349
+ help='Whether to enable a checkpoint callback and export the savedmodel.')
350
+ flags.DEFINE_string(
351
+ name='tpu', default='', help='TPU address to connect to.')
352
+ flags.DEFINE_integer(
353
+ name='steps_per_loop',
354
+ default=500,
355
+ help='Number of steps per training loop. Only training step happens '
356
+ 'inside the loop. Callbacks will not be called inside. Will be capped at '
357
+ 'steps per epoch.')
358
+ flags.DEFINE_boolean(
359
+ name='use_tf_while_loop',
360
+ default=True,
361
+ help='Whether to build a tf.while_loop inside the training loop on the '
362
+ 'host. Setting it to True is critical to have peak performance on '
363
+ 'TPU.')
364
+ flags.DEFINE_string(
365
+ 'optimizer', 'SGD',
366
+ 'Name of optimizer preset. (SGD, LARS)')
367
+ flags.DEFINE_float(
368
+ 'label_smoothing', 0.0,
369
+ 'Apply label smoothing to the loss. This applies to '
370
+ 'categorical_cross_entropy; when label_smoothing > 0, '
371
+ 'one-hot encoding is used for the labels.')
372
+ flags.DEFINE_integer('eval_offset_epochs', 0,
373
+ 'Epoch number of the first evaluation.')
374
+
375
+ if model:
376
+ flags.DEFINE_string('model', 'resnet50_v1.5',
377
+ 'Name of model preset. (mobilenet, resnet50_v1.5)')
378
+ if optimizer:
379
+ # TODO(kimjaehong): Replace as general hyper-params not only for mobilenet.
380
+ flags.DEFINE_float('initial_learning_rate_per_sample', 0.00007,
381
+ 'Initial value of learning rate per sample for '
382
+ 'mobilenet_default.')
383
+ flags.DEFINE_float('lr_decay_factor', 0.94,
384
+ 'Learning rate decay factor for mobilenet_default.')
385
+ flags.DEFINE_float('num_epochs_per_decay', 2.5,
386
+ 'Number of epochs per decay for mobilenet_default.')
387
+ if pretrained_filepath:
388
+ flags.DEFINE_string('pretrained_filepath', '',
389
+ 'Pretrained file path.')
390
+ flags.DEFINE_float('target_accuracy', None,
391
+ 'Target eval accuracy, after which training will stop.')
392
+
393
+
394
+ def get_synth_data(height, width, num_channels, num_classes, dtype):
395
+ """Creates a set of synthetic random data.
396
+
397
+ Args:
398
+ height: Integer height that will be used to create a fake image tensor.
399
+ width: Integer width that will be used to create a fake image tensor.
400
+ num_channels: Integer depth that will be used to create a fake image tensor.
401
+ num_classes: Number of classes that should be represented in the fake labels
402
+ tensor
403
+ dtype: Data type for features/images.
404
+
405
+ Returns:
406
+ A tuple of tensors representing the inputs and labels.
407
+
408
+ """
409
+ # Synthetic input should be within [0, 255].
410
+ inputs = tf.random.truncated_normal([height, width, num_channels],
411
+ dtype=dtype,
412
+ mean=127,
413
+ stddev=60,
414
+ name='synthetic_inputs')
415
+ labels = tf.random.uniform([1],
416
+ minval=0,
417
+ maxval=num_classes - 1,
418
+ dtype=tf.int32,
419
+ name='synthetic_labels')
420
+ return inputs, labels
421
+
422
+
423
+ def define_pruning_flags():
424
+ """Define flags for pruning methods."""
425
+ flags.DEFINE_string('pruning_method', None,
426
+ 'Pruning method.'
427
+ 'None (no pruning) or polynomial_decay.')
428
+ flags.DEFINE_float('pruning_initial_sparsity', 0.0,
429
+ 'Initial sparsity for pruning.')
430
+ flags.DEFINE_float('pruning_final_sparsity', 0.5,
431
+ 'Final sparsity for pruning.')
432
+ flags.DEFINE_integer('pruning_begin_step', 0,
433
+ 'Begin step for pruning.')
434
+ flags.DEFINE_integer('pruning_end_step', 100000,
435
+ 'End step for pruning.')
436
+ flags.DEFINE_integer('pruning_frequency', 100,
437
+ 'Frequency for pruning.')
438
+
439
+
440
+ # Map string to TensorFlow dtype
441
+ DTYPE_MAP = {
442
+ "fp16": tf.float16,
443
+ "fp32": tf.float32,
444
+ "bf16": tf.bfloat16,
445
+ }
446
+
447
+
448
+ def get_dl_type(flags_obj):
449
+ return DTYPE_MAP[flags_obj.data_loader_image_type]
450
+
451
+
452
+ def define_habana_flags():
453
+ """Define HABANA specific flags."""
454
+ flags.DEFINE_enum(name="data_loader_image_type", short_name="dlit", default="fp32",
455
+ enum_values=DTYPE_MAP.keys(),
456
+ help="data loader images output type")
457
+ flags.DEFINE_boolean(name='experimental_preloading', default=False,
458
+ help=help_wrap("Support for data.experimental.prefetch_to_device TensorFlow operator."
459
+ "This feature is experimental and works only with single node."
460
+ "See `-x` switch for `demo_resnet50` script."))
461
+ flags.DEFINE_boolean("use_horovod", default=False, help="Use horovod")
462
+ flags.DEFINE_boolean("modeling", default=False, help="Write graph to graph.pbtxt in model dir and export meta graph when enabled.")
463
+
464
+
465
+ def get_synth_input_fn(height, width, num_channels, num_classes,
466
+ dtype=tf.float32, drop_remainder=True,
467
+ experimental_preloading=False):
468
+ """Returns an input function that returns a dataset with random data.
469
+
470
+ This input_fn returns a data set that iterates over a set of random data and
471
+ bypasses all preprocessing, e.g. jpeg decode and copy. The host to device
472
+ copy is still included. This used to find the upper throughput bound when
473
+ tuning the full input pipeline.
474
+
475
+ Args:
476
+ height: Integer height that will be used to create a fake image tensor.
477
+ width: Integer width that will be used to create a fake image tensor.
478
+ num_channels: Integer depth that will be used to create a fake image tensor.
479
+ num_classes: Number of classes that should be represented in the fake labels
480
+ tensor
481
+ dtype: Data type for features/images.
482
+ drop_remainder: A boolean indicates whether to drop the remainder of the
483
+ batches. If True, the batch dimension will be static.
484
+
485
+ Returns:
486
+ An input_fn that can be used in place of a real one to return a dataset
487
+ that can be used for iteration.
488
+ """
489
+ # pylint: disable=unused-argument
490
+ def input_fn(is_training, data_dir, batch_size, *args, **kwargs):
491
+ """Returns dataset filled with random data."""
492
+ inputs, labels = get_synth_data(height=height,
493
+ width=width,
494
+ num_channels=num_channels,
495
+ num_classes=num_classes,
496
+ dtype=dtype)
497
+ # Cast to float32 for Keras model.
498
+ labels = tf.cast(labels, dtype=tf.float32)
499
+ data = tf.data.Dataset.from_tensors((inputs, labels)).repeat()
500
+
501
+ # `drop_remainder` will make dataset produce outputs with known shapes.
502
+ data = data.batch(batch_size, drop_remainder=drop_remainder)
503
+ if experimental_preloading:
504
+ device = "/device:HPU:0"
505
+ with tf.device(device):
506
+ data = data.apply(tf.data.experimental.prefetch_to_device(device))
507
+ else:
508
+ data = data.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
509
+ return data
510
+
511
+ return input_fn
512
+
513
+
514
+ def set_cudnn_batchnorm_mode():
515
+ """Set CuDNN batchnorm mode for better performance.
516
+
517
+ Note: Spatial Persistent mode may lead to accuracy losses for certain
518
+ models.
519
+ """
520
+ if FLAGS.batchnorm_spatial_persistent:
521
+ os.environ['TF_USE_CUDNN_BATCHNORM_SPATIAL_PERSISTENT'] = '1'
522
+ else:
523
+ os.environ.pop('TF_USE_CUDNN_BATCHNORM_SPATIAL_PERSISTENT', None)
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/mlp_log.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 MLBenchmark Group. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """Convenience function for logging compliance tags to stdout.
16
+ """
17
+
18
+ from __future__ import absolute_import
19
+ from __future__ import division
20
+ from __future__ import print_function
21
+
22
+
23
+ import inspect
24
+ import json
25
+ import logging
26
+ import os
27
+ import re
28
+ import sys
29
+ import time
30
+
31
+ try:
32
+ import horovod.tensorflow as hvd
33
+ except ImportError:
34
+ hvd = None
35
+
36
+ def get_mllog_mlloger(output_dir=None):
37
+ from mlperf_logging import mllog
38
+
39
+ if hvd is not None and hvd.is_initialized():
40
+ str_hvd_rank = str(hvd.rank())
41
+ else:
42
+ str_hvd_rank = "0"
43
+ mllogger = mllog.get_mllogger()
44
+ mllogger.propagate = False
45
+ mllog.propagate=False
46
+ if output_dir is None: output_dir='./log'
47
+ filenames = os.path.normpath(output_dir) + "/result_rank_" + str_hvd_rank + ".txt"
48
+ mllog.config(filename=filenames)
49
+ workername = "worker" + str_hvd_rank
50
+ mllog.config(
51
+ default_namespace = workername,
52
+ default_stack_offset = 1,
53
+ default_clear_line = False,
54
+ root_dir = os.path.normpath(
55
+ os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "..")))
56
+
57
+ return mllogger, mllog
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/mlperf_variable_map.json ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "conv1/kernel": "conv0_weight",
3
+ "bn_conv1/gamma": "bn0_gamma",
4
+ "bn_conv1/beta": "bn0_beta",
5
+ "res2a_branch2a/kernel": "stage1_unit1_conv1_weight",
6
+ "bn2a_branch2a/gamma": "stage1_unit1_bn1_gamma",
7
+ "bn2a_branch2a/beta": "stage1_unit1_bn1_beta",
8
+ "res2a_branch2b/kernel": "stage1_unit1_conv2_weight",
9
+ "bn2a_branch2b/gamma": "stage1_unit1_bn2_gamma",
10
+ "bn2a_branch2b/beta": "stage1_unit1_bn2_beta",
11
+ "res2a_branch2c/kernel": "stage1_unit1_conv3_weight",
12
+ "bn2a_branch2c/gamma": "stage1_unit1_bn3_gamma",
13
+ "bn2a_branch2c/beta": "stage1_unit1_bn3_beta",
14
+ "res2a_branch1/kernel": "stage1_unit1_conv1sc_weight",
15
+ "bn2a_branch1/gamma": "stage1_unit1_bnsc_gamma",
16
+ "bn2a_branch1/beta": "stage1_unit1_bnsc_beta",
17
+ "res2b_branch2a/kernel": "stage1_unit2_conv1_weight",
18
+ "bn2b_branch2a/gamma": "stage1_unit2_bn1_gamma",
19
+ "bn2b_branch2a/beta": "stage1_unit2_bn1_beta",
20
+ "res2b_branch2b/kernel": "stage1_unit2_conv2_weight",
21
+ "bn2b_branch2b/gamma": "stage1_unit2_bn2_gamma",
22
+ "bn2b_branch2b/beta": "stage1_unit2_bn2_beta",
23
+ "res2b_branch2c/kernel": "stage1_unit2_conv3_weight",
24
+ "bn2b_branch2c/gamma": "stage1_unit2_bn3_gamma",
25
+ "bn2b_branch2c/beta": "stage1_unit2_bn3_beta",
26
+ "res2c_branch2a/kernel": "stage1_unit3_conv1_weight",
27
+ "bn2c_branch2a/gamma": "stage1_unit3_bn1_gamma",
28
+ "bn2c_branch2a/beta": "stage1_unit3_bn1_beta",
29
+ "res2c_branch2b/kernel": "stage1_unit3_conv2_weight",
30
+ "bn2c_branch2b/gamma": "stage1_unit3_bn2_gamma",
31
+ "bn2c_branch2b/beta": "stage1_unit3_bn2_beta",
32
+ "res2c_branch2c/kernel": "stage1_unit3_conv3_weight",
33
+ "bn2c_branch2c/gamma": "stage1_unit3_bn3_gamma",
34
+ "bn2c_branch2c/beta": "stage1_unit3_bn3_beta",
35
+ "res3a_branch2a/kernel": "stage2_unit1_conv1_weight",
36
+ "bn3a_branch2a/gamma": "stage2_unit1_bn1_gamma",
37
+ "bn3a_branch2a/beta": "stage2_unit1_bn1_beta",
38
+ "res3a_branch2b/kernel": "stage2_unit1_conv2_weight",
39
+ "bn3a_branch2b/gamma": "stage2_unit1_bn2_gamma",
40
+ "bn3a_branch2b/beta": "stage2_unit1_bn2_beta",
41
+ "res3a_branch2c/kernel": "stage2_unit1_conv3_weight",
42
+ "bn3a_branch2c/gamma": "stage2_unit1_bn3_gamma",
43
+ "bn3a_branch2c/beta": "stage2_unit1_bn3_beta",
44
+ "res3a_branch1/kernel": "stage2_unit1_conv1sc_weight",
45
+ "bn3a_branch1/gamma": "stage2_unit1_bnsc_gamma",
46
+ "bn3a_branch1/beta": "stage2_unit1_bnsc_beta",
47
+ "res3b_branch2a/kernel": "stage2_unit2_conv1_weight",
48
+ "bn3b_branch2a/gamma": "stage2_unit2_bn1_gamma",
49
+ "bn3b_branch2a/beta": "stage2_unit2_bn1_beta",
50
+ "res3b_branch2b/kernel": "stage2_unit2_conv2_weight",
51
+ "bn3b_branch2b/gamma": "stage2_unit2_bn2_gamma",
52
+ "bn3b_branch2b/beta": "stage2_unit2_bn2_beta",
53
+ "res3b_branch2c/kernel": "stage2_unit2_conv3_weight",
54
+ "bn3b_branch2c/gamma": "stage2_unit2_bn3_gamma",
55
+ "bn3b_branch2c/beta": "stage2_unit2_bn3_beta",
56
+ "res3c_branch2a/kernel": "stage2_unit3_conv1_weight",
57
+ "bn3c_branch2a/gamma": "stage2_unit3_bn1_gamma",
58
+ "bn3c_branch2a/beta": "stage2_unit3_bn1_beta",
59
+ "res3c_branch2b/kernel": "stage2_unit3_conv2_weight",
60
+ "bn3c_branch2b/gamma": "stage2_unit3_bn2_gamma",
61
+ "bn3c_branch2b/beta": "stage2_unit3_bn2_beta",
62
+ "res3c_branch2c/kernel": "stage2_unit3_conv3_weight",
63
+ "bn3c_branch2c/gamma": "stage2_unit3_bn3_gamma",
64
+ "bn3c_branch2c/beta": "stage2_unit3_bn3_beta",
65
+ "res3d_branch2a/kernel": "stage2_unit4_conv1_weight",
66
+ "bn3d_branch2a/gamma": "stage2_unit4_bn1_gamma",
67
+ "bn3d_branch2a/beta": "stage2_unit4_bn1_beta",
68
+ "res3d_branch2b/kernel": "stage2_unit4_conv2_weight",
69
+ "bn3d_branch2b/gamma": "stage2_unit4_bn2_gamma",
70
+ "bn3d_branch2b/beta": "stage2_unit4_bn2_beta",
71
+ "res3d_branch2c/kernel": "stage2_unit4_conv3_weight",
72
+ "bn3d_branch2c/gamma": "stage2_unit4_bn3_gamma",
73
+ "bn3d_branch2c/beta": "stage2_unit4_bn3_beta",
74
+ "res4a_branch2a/kernel": "stage3_unit1_conv1_weight",
75
+ "bn4a_branch2a/gamma": "stage3_unit1_bn1_gamma",
76
+ "bn4a_branch2a/beta": "stage3_unit1_bn1_beta",
77
+ "res4a_branch2b/kernel": "stage3_unit1_conv2_weight",
78
+ "bn4a_branch2b/gamma": "stage3_unit1_bn2_gamma",
79
+ "bn4a_branch2b/beta": "stage3_unit1_bn2_beta",
80
+ "res4a_branch2c/kernel": "stage3_unit1_conv3_weight",
81
+ "bn4a_branch2c/gamma": "stage3_unit1_bn3_gamma",
82
+ "bn4a_branch2c/beta": "stage3_unit1_bn3_beta",
83
+ "res4a_branch1/kernel": "stage3_unit1_conv1sc_weight",
84
+ "bn4a_branch1/gamma": "stage3_unit1_bnsc_gamma",
85
+ "bn4a_branch1/beta": "stage3_unit1_bnsc_beta",
86
+ "res4b_branch2a/kernel": "stage3_unit2_conv1_weight",
87
+ "bn4b_branch2a/gamma": "stage3_unit2_bn1_gamma",
88
+ "bn4b_branch2a/beta": "stage3_unit2_bn1_beta",
89
+ "res4b_branch2b/kernel": "stage3_unit2_conv2_weight",
90
+ "bn4b_branch2b/gamma": "stage3_unit2_bn2_gamma",
91
+ "bn4b_branch2b/beta": "stage3_unit2_bn2_beta",
92
+ "res4b_branch2c/kernel": "stage3_unit2_conv3_weight",
93
+ "bn4b_branch2c/gamma": "stage3_unit2_bn3_gamma",
94
+ "bn4b_branch2c/beta": "stage3_unit2_bn3_beta",
95
+ "res4c_branch2a/kernel": "stage3_unit3_conv1_weight",
96
+ "bn4c_branch2a/gamma": "stage3_unit3_bn1_gamma",
97
+ "bn4c_branch2a/beta": "stage3_unit3_bn1_beta",
98
+ "res4c_branch2b/kernel": "stage3_unit3_conv2_weight",
99
+ "bn4c_branch2b/gamma": "stage3_unit3_bn2_gamma",
100
+ "bn4c_branch2b/beta": "stage3_unit3_bn2_beta",
101
+ "res4c_branch2c/kernel": "stage3_unit3_conv3_weight",
102
+ "bn4c_branch2c/gamma": "stage3_unit3_bn3_gamma",
103
+ "bn4c_branch2c/beta": "stage3_unit3_bn3_beta",
104
+ "res4d_branch2a/kernel": "stage3_unit4_conv1_weight",
105
+ "bn4d_branch2a/gamma": "stage3_unit4_bn1_gamma",
106
+ "bn4d_branch2a/beta": "stage3_unit4_bn1_beta",
107
+ "res4d_branch2b/kernel": "stage3_unit4_conv2_weight",
108
+ "bn4d_branch2b/gamma": "stage3_unit4_bn2_gamma",
109
+ "bn4d_branch2b/beta": "stage3_unit4_bn2_beta",
110
+ "res4d_branch2c/kernel": "stage3_unit4_conv3_weight",
111
+ "bn4d_branch2c/gamma": "stage3_unit4_bn3_gamma",
112
+ "bn4d_branch2c/beta": "stage3_unit4_bn3_beta",
113
+ "res4e_branch2a/kernel": "stage3_unit5_conv1_weight",
114
+ "bn4e_branch2a/gamma": "stage3_unit5_bn1_gamma",
115
+ "bn4e_branch2a/beta": "stage3_unit5_bn1_beta",
116
+ "res4e_branch2b/kernel": "stage3_unit5_conv2_weight",
117
+ "bn4e_branch2b/gamma": "stage3_unit5_bn2_gamma",
118
+ "bn4e_branch2b/beta": "stage3_unit5_bn2_beta",
119
+ "res4e_branch2c/kernel": "stage3_unit5_conv3_weight",
120
+ "bn4e_branch2c/gamma": "stage3_unit5_bn3_gamma",
121
+ "bn4e_branch2c/beta": "stage3_unit5_bn3_beta",
122
+ "res4f_branch2a/kernel": "stage3_unit6_conv1_weight",
123
+ "bn4f_branch2a/gamma": "stage3_unit6_bn1_gamma",
124
+ "bn4f_branch2a/beta": "stage3_unit6_bn1_beta",
125
+ "res4f_branch2b/kernel": "stage3_unit6_conv2_weight",
126
+ "bn4f_branch2b/gamma": "stage3_unit6_bn2_gamma",
127
+ "bn4f_branch2b/beta": "stage3_unit6_bn2_beta",
128
+ "res4f_branch2c/kernel": "stage3_unit6_conv3_weight",
129
+ "bn4f_branch2c/gamma": "stage3_unit6_bn3_gamma",
130
+ "bn4f_branch2c/beta": "stage3_unit6_bn3_beta",
131
+ "res5a_branch2a/kernel": "stage4_unit1_conv1_weight",
132
+ "bn5a_branch2a/gamma": "stage4_unit1_bn1_gamma",
133
+ "bn5a_branch2a/beta": "stage4_unit1_bn1_beta",
134
+ "res5a_branch2b/kernel": "stage4_unit1_conv2_weight",
135
+ "bn5a_branch2b/gamma": "stage4_unit1_bn2_gamma",
136
+ "bn5a_branch2b/beta": "stage4_unit1_bn2_beta",
137
+ "res5a_branch2c/kernel": "stage4_unit1_conv3_weight",
138
+ "bn5a_branch2c/gamma": "stage4_unit1_bn3_gamma",
139
+ "bn5a_branch2c/beta": "stage4_unit1_bn3_beta",
140
+ "res5a_branch1/kernel": "stage4_unit1_conv1sc_weight",
141
+ "bn5a_branch1/gamma": "stage4_unit1_bnsc_gamma",
142
+ "bn5a_branch1/beta": "stage4_unit1_bnsc_beta",
143
+ "res5b_branch2a/kernel": "stage4_unit2_conv1_weight",
144
+ "bn5b_branch2a/gamma": "stage4_unit2_bn1_gamma",
145
+ "bn5b_branch2a/beta": "stage4_unit2_bn1_beta",
146
+ "res5b_branch2b/kernel": "stage4_unit2_conv2_weight",
147
+ "bn5b_branch2b/gamma": "stage4_unit2_bn2_gamma",
148
+ "bn5b_branch2b/beta": "stage4_unit2_bn2_beta",
149
+ "res5b_branch2c/kernel": "stage4_unit2_conv3_weight",
150
+ "bn5b_branch2c/gamma": "stage4_unit2_bn3_gamma",
151
+ "bn5b_branch2c/beta": "stage4_unit2_bn3_beta",
152
+ "res5c_branch2a/kernel": "stage4_unit3_conv1_weight",
153
+ "bn5c_branch2a/gamma": "stage4_unit3_bn1_gamma",
154
+ "bn5c_branch2a/beta": "stage4_unit3_bn1_beta",
155
+ "res5c_branch2b/kernel": "stage4_unit3_conv2_weight",
156
+ "bn5c_branch2b/gamma": "stage4_unit3_bn2_gamma",
157
+ "bn5c_branch2b/beta": "stage4_unit3_bn2_beta",
158
+ "res5c_branch2c/kernel": "stage4_unit3_conv3_weight",
159
+ "bn5c_branch2c/gamma": "stage4_unit3_bn3_gamma",
160
+ "bn5c_branch2c/beta": "stage4_unit3_bn3_beta",
161
+ "fc1000/kernel": "fc1_weight",
162
+ "fc1000/bias": "fc1_bias"
163
+ }
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ absl_py==1.0.0
2
+ cloudpickle==1.6.0
3
+ psutil==5.8.0
4
+ PyYAML==6.0.0
5
+ requests==2.25.1
6
+ tensorflow_model_optimization==0.7.2
7
+ git+https://github.com/mlperf/[email protected]
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/resnet_ctl_imagenet_main.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ # List of changes:
16
+ # - loading habana module
17
+ # - added support for prefetching to HPU
18
+ # - added profiling callbacks support
19
+ # - changed include paths of modules
20
+ # - include mechanism for dumping tensors
21
+
22
+ # Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company
23
+
24
+ """Runs a ResNet model on the ImageNet dataset using custom training loops."""
25
+
26
+ from __future__ import absolute_import
27
+ from __future__ import division
28
+ from __future__ import print_function
29
+ import shutil
30
+
31
+ from absl import app
32
+ from absl import flags
33
+ from absl import logging
34
+ import tensorflow as tf
35
+ import os
36
+ import math
37
+
38
+ from TensorFlow.common.modeling import performance
39
+ from TensorFlow.common.training import controller
40
+ from TensorFlow.utils.flags import core as flags_core
41
+ from TensorFlow.utils.logs import logger
42
+ from TensorFlow.utils.misc import distribution_utils
43
+ from TensorFlow.utils.misc import keras_utils
44
+ from TensorFlow.utils.misc import model_helpers
45
+ from TensorFlow.computer_vision.common import imagenet_preprocessing
46
+ from TensorFlow.computer_vision.Resnets.utils.optimizers.keras import lars_util
47
+ from TensorFlow.computer_vision.Resnets.resnet_keras import common
48
+ from TensorFlow.computer_vision.Resnets.resnet_keras import resnet_runnable
49
+ from TensorFlow.computer_vision.Resnets.resnet_keras.common import get_global_batch_size
50
+ from habana_frameworks.tensorflow import load_habana_module
51
+ from TensorFlow.common.debug import dump_callback
52
+ from TensorFlow.common.tb_utils import write_hparams_v2
53
+ from habana_frameworks.tensorflow.synapse_logger_helpers import synapse_logger_init
54
+ from TensorFlow.computer_vision.Resnets.resnet_keras.mlp_log import get_mllog_mlloger
55
+
56
+ try:
57
+ import horovod.tensorflow as hvd
58
+ except ImportError as e:
59
+ _hvd_exc = e
60
+ hvd = None
61
+
62
+ flags.DEFINE_boolean(name='use_tf_function', default=True,
63
+ help='Wrap the train and test step inside a '
64
+ 'tf.function.')
65
+ flags.DEFINE_boolean(name='single_l2_loss_op', default=False,
66
+ help='Calculate L2_loss on concatenated weights, '
67
+ 'instead of using Keras per-layer L2 loss.')
68
+ flags.DEFINE_boolean(name='cache_decoded_image',
69
+ default=False,
70
+ help='Whether or not to cache decoded images in the '
71
+ 'input pipeline. If this flag and `cache` is enabled, '
72
+ 'then TFExample protos will be parsed and then cached '
73
+ 'which reduces the load on hosts.')
74
+ flags.DEFINE_boolean(name='dist_eval', default=True,
75
+ help='Partial eval in each rank and allreduce the partial result')
76
+ flags.DEFINE_boolean(name='enable_device_warmup',
77
+ default=False,
78
+ help='Whether or not to enable device warmup. This '
79
+ 'includes training on dummy data and enabling graph/XLA '
80
+ 'compilation before run_start.')
81
+ flags.DEFINE_integer(name='device_warmup_steps',
82
+ default=2,
83
+ help='The number of steps to apply for device warmup.')
84
+ flags.DEFINE_float('base_learning_rate', 0.1,
85
+ 'Base learning rate. '
86
+ 'This is the learning rate when using batch size 256; when using other '
87
+ 'batch sizes, the learning rate will be scaled linearly.')
88
+ flags.DEFINE_boolean(name='profile', default=False,
89
+ help='Running RN50 with profiling')
90
+ flags.DEFINE_integer(name='num_train_files',
91
+ default=1024,
92
+ help='The number of training tf records.')
93
+ flags.DEFINE_integer(name='num_eval_files',
94
+ default=128,
95
+ help='The number of evaluation tf records.')
96
+ flags.DEFINE_integer(name='num_acc_steps', default=1, help='Number of gradient accumulation steps.')
97
+
98
+
99
+ def build_stats(runnable, time_callback):
100
+ """Normalizes and returns dictionary of stats.
101
+
102
+ Args:
103
+ runnable: The module containing all the training and evaluation metrics.
104
+ time_callback: Time tracking callback instance.
105
+
106
+ Returns:
107
+ Dictionary of normalized results.
108
+ """
109
+ stats = {}
110
+
111
+ if not runnable.flags_obj.skip_eval:
112
+ if runnable.test_loss:
113
+ stats['eval_loss'] = runnable.test_loss.result().numpy()
114
+ if runnable.test_accuracy:
115
+ stats['eval_acc'] = runnable.eval_accuracy
116
+
117
+ if runnable.train_loss:
118
+ stats['train_loss'] = runnable.train_loss.result().numpy()
119
+ if runnable.train_accuracy:
120
+ stats['train_acc'] = runnable.train_accuracy.result().numpy()
121
+
122
+ if time_callback:
123
+ timestamp_log = time_callback.timestamp_log
124
+ stats['step_timestamp_log'] = timestamp_log
125
+ stats['train_finish_time'] = time_callback.train_finish_time
126
+ if time_callback.epoch_runtime_log:
127
+ stats['avg_exp_per_second'] = time_callback.average_examples_per_second
128
+
129
+ return stats
130
+
131
+
132
+ def get_num_train_iterations(flags_obj):
133
+ """Returns the number of training steps, train and test epochs."""
134
+ global_batch_size = get_global_batch_size(flags_obj.batch_size, flags_obj.num_acc_steps)
135
+ steps_per_epoch = math.ceil(imagenet_preprocessing.NUM_IMAGES['train'] / global_batch_size)
136
+ train_epochs = flags_obj.train_epochs
137
+
138
+ if train_epochs == 0 and flags_obj.train_steps > 0:
139
+ steps_per_epoch = flags_obj.train_steps
140
+ train_epochs = 1
141
+
142
+ eval_batch_size = flags_obj.batch_size
143
+ if flags_obj.dist_eval:
144
+ eval_batch_size = global_batch_size
145
+ eval_steps = (
146
+ math.ceil(imagenet_preprocessing.NUM_IMAGES['validation'] / eval_batch_size))
147
+
148
+ return steps_per_epoch, train_epochs, eval_steps
149
+
150
+
151
+ def _steps_to_run(steps_in_current_epoch, steps_per_epoch, steps_per_loop):
152
+ """Calculates steps to run on device."""
153
+ if steps_per_loop <= 0:
154
+ raise ValueError('steps_per_loop should be positive integer.')
155
+ if steps_per_loop == 1:
156
+ return steps_per_loop
157
+ return min(steps_per_loop, steps_per_epoch - steps_in_current_epoch)
158
+
159
+
160
+ def run(flags_obj):
161
+ """Run ResNet ImageNet training and eval loop using custom training loops.
162
+
163
+ Args:
164
+ flags_obj: An object containing parsed flag values.
165
+
166
+ Raises:
167
+ ValueError: If fp16 is passed as it is not currently supported.
168
+
169
+ Returns:
170
+ Dictionary of training and eval stats.
171
+ """
172
+ tf.get_logger().propagate = False
173
+ output_dir = None
174
+ if "LOG_DIR" in os.environ:
175
+ output_dir = os.environ["LOG_DIR"]
176
+ mlperf_mlloger, mlperf_mllog = get_mllog_mlloger(output_dir)
177
+ mlperf_mlloger.event(key=mlperf_mllog.constants.CACHE_CLEAR, value=True)
178
+ mlperf_mlloger.start(key=mlperf_mllog.constants.INIT_START, value=None)
179
+ mlperf_mlloger.event(key=mlperf_mllog.constants.SUBMISSION_BENCHMARK, value=mlperf_mllog.constants.RESNET)
180
+ mlperf_mlloger.event(key=mlperf_mllog.constants.SUBMISSION_ORG, value='Habana')
181
+ mlperf_mlloger.event(key=mlperf_mllog.constants.SUBMISSION_DIVISION, value='closed')
182
+ mlperf_mlloger.event(key=mlperf_mllog.constants.SUBMISSION_PLATFORM, value='gaudi-{}'.format(flags_obj.num_gpus))
183
+ mlperf_mlloger.event(key=mlperf_mllog.constants.SUBMISSION_STATUS, value='onprem')
184
+
185
+ keras_utils.set_session_config(
186
+ enable_eager=flags_obj.enable_eager,
187
+ enable_xla=flags_obj.enable_xla)
188
+ performance.set_mixed_precision_policy(flags_core.get_tf_dtype(flags_obj))
189
+
190
+ # This only affects GPU.
191
+ common.set_cudnn_batchnorm_mode()
192
+
193
+ # TODO(anj-s): Set data_format without using Keras.
194
+ data_format = flags_obj.data_format
195
+ if data_format is None:
196
+ data_format = ('channels_first'
197
+ if tf.test.is_built_with_cuda() else 'channels_last')
198
+ tf.keras.backend.set_image_data_format(data_format)
199
+
200
+ if hvd is not None and hvd.is_initialized():
201
+ model_dir = os.path.join(
202
+ flags_obj.model_dir, "worker_" + str(hvd.rank()))
203
+ else:
204
+ model_dir = flags_obj.model_dir
205
+
206
+ global_batch_size = get_global_batch_size(flags_obj.batch_size, flags_obj.num_acc_steps)
207
+
208
+ strategy = distribution_utils.get_distribution_strategy(
209
+ distribution_strategy=flags_obj.distribution_strategy,
210
+ num_gpus=flags_obj.num_gpus,
211
+ all_reduce_alg=flags_obj.all_reduce_alg,
212
+ num_packs=flags_obj.num_packs,
213
+ tpu_address=flags_obj.tpu)
214
+
215
+ mlperf_mlloger.event(key=mlperf_mllog.constants.GLOBAL_BATCH_SIZE, value=global_batch_size)
216
+ mlperf_mlloger.event(key=mlperf_mllog.constants.TRAIN_SAMPLES, value=imagenet_preprocessing.NUM_IMAGES['train'])
217
+ mlperf_mlloger.event(key=mlperf_mllog.constants.EVAL_SAMPLES, value=imagenet_preprocessing.NUM_IMAGES['validation'])
218
+ group_batch_norm = 1
219
+ mlperf_mlloger.event(key=mlperf_mllog.constants.MODEL_BN_SPAN, value= flags_obj.batch_size * group_batch_norm)
220
+ mlperf_mlloger.event(key=mlperf_mllog.constants.GRADIENT_ACCUMULATION_STEPS, value= flags_obj.num_acc_steps)
221
+
222
+ train_writer, eval_writer = None, None
223
+ if flags_obj.enable_tensorboard:
224
+ train_writer = tf.summary.create_file_writer(model_dir)
225
+ eval_writer = tf.summary.create_file_writer(os.path.join(model_dir, 'eval'))
226
+ hparams = flags_obj.flag_values_dict()
227
+ write_hparams_v2(train_writer, hparams)
228
+
229
+ per_epoch_steps, train_epochs, eval_steps = get_num_train_iterations(
230
+ flags_obj)
231
+ steps_per_loop = min(flags_obj.steps_per_loop, per_epoch_steps)
232
+ train_steps = train_epochs * per_epoch_steps
233
+
234
+ logging.info(
235
+ 'Training %d epochs, each epoch has %d steps, '
236
+ 'total steps: %d; Eval %d steps', train_epochs, per_epoch_steps,
237
+ train_steps, eval_steps)
238
+
239
+ time_callback = keras_utils.TimeHistory(
240
+ global_batch_size,
241
+ flags_obj.log_steps,
242
+ summary_writer=train_writer,
243
+ batch_size_per_node=flags_obj.batch_size)
244
+ profiler_callback = None
245
+ if flags_obj.profile_steps is not None:
246
+ profiler_callback = keras_utils.get_profiler_callback(
247
+ model_dir,
248
+ flags_obj.profile_steps,
249
+ flags_obj.enable_tensorboard,
250
+ per_epoch_steps)
251
+ with distribution_utils.get_strategy_scope(strategy):
252
+ runnable = resnet_runnable.ResnetRunnable(flags_obj, time_callback,
253
+ train_steps,
254
+ per_epoch_steps,
255
+ profiler_callback,mlperf_mlloger,mlperf_mllog)
256
+
257
+ eval_interval = flags_obj.epochs_between_evals * per_epoch_steps
258
+ eval_offset = flags_obj.eval_offset_epochs * per_epoch_steps
259
+ if eval_offset != 0:
260
+ eval_offset -= eval_interval
261
+ checkpoint_interval = (
262
+ per_epoch_steps if flags_obj.enable_checkpoint_and_export else None)
263
+ summary_interval = per_epoch_steps if flags_obj.enable_tensorboard else None
264
+
265
+ checkpoint_manager = tf.train.CheckpointManager(
266
+ runnable.checkpoint,
267
+ directory=model_dir,
268
+ max_to_keep=10,
269
+ step_counter=runnable.global_step,
270
+ checkpoint_interval=checkpoint_interval)
271
+
272
+ device_warmup_steps = (
273
+ flags_obj.device_warmup_steps if flags_obj.enable_device_warmup else 0)
274
+
275
+ if flags_obj.enable_device_warmup:
276
+ logging.info('Warmup for %d steps.', device_warmup_steps)
277
+
278
+ train_steps=per_epoch_steps * train_epochs
279
+
280
+ resnet_controller = controller.Controller(
281
+ strategy,
282
+ runnable.train,
283
+ runnable.evaluate,
284
+ runnable.warmup,
285
+ global_step=runnable.global_step,
286
+ steps_per_loop=steps_per_loop,
287
+ train_steps=train_steps,
288
+ checkpoint_manager=checkpoint_manager,
289
+ summary_interval=summary_interval,
290
+ eval_steps=eval_steps,
291
+ eval_interval=eval_interval,
292
+ eval_offset=eval_offset,
293
+ device_warmup_steps=device_warmup_steps,
294
+ train_summary_writer=train_writer,
295
+ eval_summary_writer=eval_writer)
296
+
297
+ if flags_obj.enable_device_warmup:
298
+ resnet_controller.warmup()
299
+ del runnable.warmup_train_iter
300
+ del runnable.warmup_train_dataset
301
+ del runnable.warmup_eval_iter
302
+ del runnable.warmup_eval_dataset
303
+ try:
304
+ synth_data_dir = f'{model_dir}/resnet_synth_data'
305
+ shutil.rmtree(synth_data_dir)
306
+ except:
307
+ pass
308
+
309
+ manifest_path = prepare_dataset_manifest(flags_obj)
310
+
311
+ mlperf_mlloger.end(key=mlperf_mllog.constants.INIT_STOP)
312
+
313
+ if flags.FLAGS.use_horovod:
314
+ hvd.broadcast(0, 0)
315
+ time_callback.on_train_begin()
316
+ mlperf_mlloger.start(key=mlperf_mllog.constants.RUN_START)
317
+ mlperf_mlloger.start(
318
+ key=mlperf_mllog.constants.BLOCK_START, value=None,
319
+ metadata={
320
+ 'first_epoch_num': 1,
321
+ 'epoch_count':
322
+ (flags_obj.eval_offset_epochs if flags_obj.eval_offset_epochs > 0
323
+ else flags_obj.epochs_between_evals)
324
+ })
325
+ resnet_controller.train(evaluate=not flags_obj.skip_eval, num_acc_steps=flags_obj.num_acc_steps, manifest_path=manifest_path)
326
+ if not flags_obj.skip_eval:
327
+ eval_accuracy = resnet_controller.last_eval_output['test_accuracy']
328
+ if eval_accuracy >= flags_obj.target_accuracy:
329
+ mlperf_mlloger.end(key=mlperf_mllog.constants.RUN_STOP, value=None, metadata={'status': 'success'})
330
+ else:
331
+ mlperf_mlloger.end(key=mlperf_mllog.constants.RUN_STOP, value=None, metadata={'status': 'fail'})
332
+ time_callback.on_train_end()
333
+
334
+
335
+ stats = build_stats(runnable, time_callback)
336
+ return stats
337
+
338
+
339
+ def prepare_dataset_manifest(flags_obj):
340
+ import glob
341
+ import json
342
+ import pathlib
343
+
344
+ from habana_frameworks.tensorflow.multinode_helpers import comm_rank
345
+
346
+ manifest_file_name = f"imagenet_jpeg_manifest_rank_{comm_rank()}.json"
347
+ manifest_path = os.path.join('/tmp', manifest_file_name)
348
+
349
+ if flags_obj.jpeg_data_dir is not None:
350
+ # get files list
351
+ dataset_dir = os.path.join(flags_obj.jpeg_data_dir, 'train')
352
+
353
+ print(f"dataset dir: {dataset_dir}")
354
+ manifest_data = {}
355
+ manifest_data["file_list"] = sorted(
356
+ glob.glob(dataset_dir + "/*/*.{}".format("JPEG")))
357
+
358
+ # get class list
359
+ data_dir = pathlib.Path(dataset_dir)
360
+ manifest_data["class_list"] = sorted(
361
+ [item.name for item in data_dir.glob('*') if item.is_dir() == True])
362
+
363
+ file_sizes = {}
364
+ file_classes = []
365
+
366
+ for filename in manifest_data["file_list"]:
367
+ #Everything is in order as file_list is sorted
368
+ file_sizes[filename] = os.stat(filename).st_size
369
+ file_classes.append(os.path.basename(os.path.dirname(filename)))
370
+
371
+ manifest_data['file_sizes'] = file_sizes
372
+ manifest_data['file_classes'] = file_classes
373
+
374
+ with open(manifest_path, "w") as f:
375
+ json.dump(manifest_data, f)
376
+
377
+ return manifest_path
378
+
379
+
380
+ def main(_):
381
+ if flags.FLAGS.use_horovod:
382
+ if hvd is None:
383
+ logging.error("Problem encountered during Horovod import. Please make sure that habana-horovod package is installed.")
384
+ raise _hvd_exc
385
+ hvd.init()
386
+ else:
387
+ synapse_logger_init()
388
+
389
+ os.environ['TF_EXPERIMENTAL_BATCH_VARIABLES'] = '1'
390
+ os.environ['TF_CLUSTER_VARIABLES'] = '1'
391
+ load_habana_module()
392
+
393
+ with dump_callback():
394
+ model_helpers.apply_clean(flags.FLAGS)
395
+ with logger.benchmark_context(flags.FLAGS):
396
+ stats =run (flags.FLAGS)
397
+ logging.info('Run stats:\n%s', stats)
398
+
399
+
400
+ if __name__ == '__main__':
401
+ logging.set_verbosity(logging.INFO)
402
+ common.define_keras_flags()
403
+ common.define_habana_flags()
404
+ lars_util.define_lars_flags()
405
+ app.run(main)
406
+
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/resnet_model.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """ResNet50 model for Keras.
16
+ Adapted from tf.keras.applications.resnet50.ResNet50().
17
+ This is ResNet model version 1.5.
18
+ Related papers/blogs:
19
+ - https://arxiv.org/abs/1512.03385
20
+ - https://arxiv.org/pdf/1603.05027v2.pdf
21
+ - http://torch.ch/blog/2016/02/04/resnets.html
22
+ """
23
+ from __future__ import absolute_import
24
+ from __future__ import division
25
+ from __future__ import print_function
26
+
27
+ from absl import flags
28
+ import tensorflow as tf
29
+ from TensorFlow.computer_vision.common import imagenet_preprocessing
30
+
31
+ FLAGS = flags.FLAGS
32
+ flags.DEFINE_float(
33
+ 'weight_decay',
34
+ default=1e-4,
35
+ help=('Weight decay coefficiant for l2 regularization.'))
36
+
37
+ layers = tf.keras.layers
38
+
39
+
40
+ def _gen_l2_regularizer(use_l2_regularizer=True):
41
+ return tf.keras.regularizers.L2(
42
+ FLAGS.weight_decay) if use_l2_regularizer else None
43
+
44
+
45
+ def identity_block(input_tensor,
46
+ kernel_size,
47
+ filters,
48
+ stage,
49
+ block,
50
+ use_l2_regularizer=True,
51
+ batch_norm_decay=0.9,
52
+ batch_norm_epsilon=1e-5):
53
+ """The identity block is the block that has no conv layer at shortcut.
54
+ Args:
55
+ input_tensor: input tensor
56
+ kernel_size: default 3, the kernel size of middle conv layer at main path
57
+ filters: list of integers, the filters of 3 conv layer at main path
58
+ stage: integer, current stage label, used for generating layer names
59
+ block: 'a','b'..., current block label, used for generating layer names
60
+ use_l2_regularizer: whether to use L2 regularizer on Conv layer.
61
+ batch_norm_decay: Moment of batch norm layers.
62
+ batch_norm_epsilon: Epsilon of batch borm layers.
63
+ Returns:
64
+ Output tensor for the block.
65
+ """
66
+ filters1, filters2, filters3 = filters
67
+ if tf.keras.backend.image_data_format() == 'channels_last':
68
+ bn_axis = 3
69
+ else:
70
+ bn_axis = 1
71
+ conv_name_base = 'res' + str(stage) + block + '_branch'
72
+ bn_name_base = 'bn' + str(stage) + block + '_branch'
73
+
74
+ x = layers.Conv2D(
75
+ filters1, (1, 1),
76
+ use_bias=False,
77
+ kernel_initializer='he_normal',
78
+ kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer),
79
+ name=conv_name_base + '2a')(
80
+ input_tensor)
81
+ x = layers.BatchNormalization(
82
+ axis=bn_axis,
83
+ momentum=batch_norm_decay,
84
+ epsilon=batch_norm_epsilon,
85
+ name=bn_name_base + '2a')(
86
+ x)
87
+ x = layers.Activation('relu')(x)
88
+
89
+ x = layers.Conv2D(
90
+ filters2,
91
+ kernel_size,
92
+ padding='same',
93
+ use_bias=False,
94
+ kernel_initializer='he_normal',
95
+ kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer),
96
+ name=conv_name_base + '2b')(
97
+ x)
98
+ x = layers.BatchNormalization(
99
+ axis=bn_axis,
100
+ momentum=batch_norm_decay,
101
+ epsilon=batch_norm_epsilon,
102
+ name=bn_name_base + '2b')(
103
+ x)
104
+ x = layers.Activation('relu')(x)
105
+
106
+ x = layers.Conv2D(
107
+ filters3, (1, 1),
108
+ use_bias=False,
109
+ kernel_initializer='he_normal',
110
+ kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer),
111
+ name=conv_name_base + '2c')(
112
+ x)
113
+ x = layers.BatchNormalization(
114
+ axis=bn_axis,
115
+ momentum=batch_norm_decay,
116
+ epsilon=batch_norm_epsilon,
117
+ name=bn_name_base + '2c')(
118
+ x)
119
+
120
+ x = layers.add([x, input_tensor])
121
+ x = layers.Activation('relu')(x)
122
+ return x
123
+
124
+
125
+ def conv_block(input_tensor,
126
+ kernel_size,
127
+ filters,
128
+ stage,
129
+ block,
130
+ strides=(2, 2),
131
+ use_l2_regularizer=True,
132
+ batch_norm_decay=0.9,
133
+ batch_norm_epsilon=1e-5):
134
+ """A block that has a conv layer at shortcut.
135
+ Note that from stage 3,
136
+ the second conv layer at main path is with strides=(2, 2)
137
+ And the shortcut should have strides=(2, 2) as well
138
+ Args:
139
+ input_tensor: input tensor
140
+ kernel_size: default 3, the kernel size of middle conv layer at main path
141
+ filters: list of integers, the filters of 3 conv layer at main path
142
+ stage: integer, current stage label, used for generating layer names
143
+ block: 'a','b'..., current block label, used for generating layer names
144
+ strides: Strides for the second conv layer in the block.
145
+ use_l2_regularizer: whether to use L2 regularizer on Conv layer.
146
+ batch_norm_decay: Moment of batch norm layers.
147
+ batch_norm_epsilon: Epsilon of batch borm layers.
148
+ Returns:
149
+ Output tensor for the block.
150
+ """
151
+ filters1, filters2, filters3 = filters
152
+ if tf.keras.backend.image_data_format() == 'channels_last':
153
+ bn_axis = 3
154
+ else:
155
+ bn_axis = 1
156
+ conv_name_base = 'res' + str(stage) + block + '_branch'
157
+ bn_name_base = 'bn' + str(stage) + block + '_branch'
158
+
159
+ x = layers.Conv2D(
160
+ filters1, (1, 1),
161
+ use_bias=False,
162
+ kernel_initializer='he_normal',
163
+ kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer),
164
+ name=conv_name_base + '2a')(
165
+ input_tensor)
166
+ x = layers.BatchNormalization(
167
+ axis=bn_axis,
168
+ momentum=batch_norm_decay,
169
+ epsilon=batch_norm_epsilon,
170
+ name=bn_name_base + '2a')(
171
+ x)
172
+ x = layers.Activation('relu')(x)
173
+
174
+ x = layers.Conv2D(
175
+ filters2,
176
+ kernel_size,
177
+ strides=strides,
178
+ padding='same',
179
+ use_bias=False,
180
+ kernel_initializer='he_normal',
181
+ kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer),
182
+ name=conv_name_base + '2b')(
183
+ x)
184
+ x = layers.BatchNormalization(
185
+ axis=bn_axis,
186
+ momentum=batch_norm_decay,
187
+ epsilon=batch_norm_epsilon,
188
+ name=bn_name_base + '2b')(
189
+ x)
190
+ x = layers.Activation('relu')(x)
191
+
192
+ x = layers.Conv2D(
193
+ filters3, (1, 1),
194
+ use_bias=False,
195
+ kernel_initializer='he_normal',
196
+ kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer),
197
+ name=conv_name_base + '2c')(
198
+ x)
199
+ x = layers.BatchNormalization(
200
+ axis=bn_axis,
201
+ momentum=batch_norm_decay,
202
+ epsilon=batch_norm_epsilon,
203
+ name=bn_name_base + '2c')(
204
+ x)
205
+
206
+ shortcut = layers.Conv2D(
207
+ filters3, (1, 1),
208
+ strides=strides,
209
+ use_bias=False,
210
+ kernel_initializer='he_normal',
211
+ kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer),
212
+ name=conv_name_base + '1')(
213
+ input_tensor)
214
+ shortcut = layers.BatchNormalization(
215
+ axis=bn_axis,
216
+ momentum=batch_norm_decay,
217
+ epsilon=batch_norm_epsilon,
218
+ name=bn_name_base + '1')(
219
+ shortcut)
220
+
221
+ x = layers.add([x, shortcut])
222
+ x = layers.Activation('relu')(x)
223
+ return x
224
+
225
+
226
+ def resnet50(num_classes,
227
+ batch_size=None,
228
+ use_l2_regularizer=True,
229
+ rescale_inputs=False,
230
+ batch_norm_decay=0.9,
231
+ batch_norm_epsilon=1e-5):
232
+ """Instantiates the ResNet50 architecture.
233
+ Args:
234
+ num_classes: `int` number of classes for image classification.
235
+ batch_size: Size of the batches for each step.
236
+ use_l2_regularizer: whether to use L2 regularizer on Conv/Dense layer.
237
+ rescale_inputs: whether to rescale inputs from 0 to 1.
238
+ batch_norm_decay: Moment of batch norm layers.
239
+ batch_norm_epsilon: Epsilon of batch borm layers.
240
+ Returns:
241
+ A Keras model instance.
242
+ """
243
+ input_shape = (224, 224, 3)
244
+ img_input = layers.Input(shape=input_shape, batch_size=batch_size)
245
+ if rescale_inputs:
246
+ # Hub image modules expect inputs in the range [0, 1]. This rescales these
247
+ # inputs to the range expected by the trained model.
248
+ x = layers.Lambda(
249
+ lambda x: x * 255.0 - tf.keras.backend.constant( # pylint: disable=g-long-lambda
250
+ imagenet_preprocessing.CHANNEL_MEANS,
251
+ shape=[1, 1, 3],
252
+ dtype=x.dtype),
253
+ name='rescale')(
254
+ img_input)
255
+ else:
256
+ x = img_input
257
+
258
+ if tf.keras.backend.image_data_format() == 'channels_first':
259
+ x = layers.Permute((3, 1, 2))(x)
260
+ bn_axis = 1
261
+ else: # channels_last
262
+ bn_axis = 3
263
+
264
+ block_config = dict(
265
+ use_l2_regularizer=use_l2_regularizer,
266
+ batch_norm_decay=batch_norm_decay,
267
+ batch_norm_epsilon=batch_norm_epsilon)
268
+ x = layers.ZeroPadding2D(padding=(3, 3), name='conv1_pad')(x)
269
+ x = layers.Conv2D(
270
+ 64, (7, 7),
271
+ strides=(2, 2),
272
+ padding='valid',
273
+ use_bias=False,
274
+ kernel_initializer='he_normal',
275
+ kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer),
276
+ name='conv1')(
277
+ x)
278
+ x = layers.BatchNormalization(
279
+ axis=bn_axis,
280
+ momentum=batch_norm_decay,
281
+ epsilon=batch_norm_epsilon,
282
+ name='bn_conv1')(
283
+ x)
284
+ x = layers.Activation('relu')(x)
285
+ x = layers.MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
286
+
287
+ x = conv_block(
288
+ x, 3, [64, 64, 256], stage=2, block='a', strides=(1, 1), **block_config)
289
+ x = identity_block(x, 3, [64, 64, 256], stage=2, block='b', **block_config)
290
+ x = identity_block(x, 3, [64, 64, 256], stage=2, block='c', **block_config)
291
+
292
+ x = conv_block(x, 3, [128, 128, 512], stage=3, block='a', **block_config)
293
+ x = identity_block(x, 3, [128, 128, 512], stage=3, block='b', **block_config)
294
+ x = identity_block(x, 3, [128, 128, 512], stage=3, block='c', **block_config)
295
+ x = identity_block(x, 3, [128, 128, 512], stage=3, block='d', **block_config)
296
+
297
+ x = conv_block(x, 3, [256, 256, 1024], stage=4, block='a', **block_config)
298
+ x = identity_block(x, 3, [256, 256, 1024], stage=4, block='b', **block_config)
299
+ x = identity_block(x, 3, [256, 256, 1024], stage=4, block='c', **block_config)
300
+ x = identity_block(x, 3, [256, 256, 1024], stage=4, block='d', **block_config)
301
+ x = identity_block(x, 3, [256, 256, 1024], stage=4, block='e', **block_config)
302
+ x = identity_block(x, 3, [256, 256, 1024], stage=4, block='f', **block_config)
303
+
304
+ x = conv_block(x, 3, [512, 512, 2048], stage=5, block='a', **block_config)
305
+ x = identity_block(x, 3, [512, 512, 2048], stage=5, block='b', **block_config)
306
+ x = identity_block(x, 3, [512, 512, 2048], stage=5, block='c', **block_config)
307
+
308
+ x = layers.GlobalAveragePooling2D()(x)
309
+ x = layers.Dense(
310
+ num_classes,
311
+ kernel_initializer=tf.compat.v1.keras.initializers.random_normal(
312
+ stddev=0.01),
313
+ kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer),
314
+ bias_regularizer=_gen_l2_regularizer(use_l2_regularizer),
315
+ name='fc1000')(
316
+ x)
317
+
318
+ # A softmax that is followed by the model loss must be done cannot be done
319
+ # in float16 due to numeric issues. So we pass dtype=float32.
320
+ x = layers.Activation('softmax', dtype='float32')(x)
321
+
322
+ # Create model.
323
+ return tf.keras.Model(img_input, x, name='resnet50')
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/resnet_keras/resnet_runnable.py ADDED
@@ -0,0 +1,545 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ # List of changes:
16
+ # - added profiling callbacks support
17
+
18
+ # Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company
19
+
20
+ """Runs a ResNet model on the ImageNet dataset using custom training loops."""
21
+
22
+ from __future__ import absolute_import
23
+ from __future__ import division
24
+ from __future__ import print_function
25
+
26
+ import json
27
+ import os
28
+ from typing import Dict, Optional, Text
29
+
30
+ import tensorflow as tf
31
+ from TensorFlow.common.modeling import performance
32
+ from TensorFlow.common.training import grad_utils
33
+ from TensorFlow.common.training import standard_runnable
34
+ from TensorFlow.common.training import utils
35
+ from TensorFlow.utils.flags import core as flags_core
36
+ from TensorFlow.computer_vision.common import imagenet_preprocessing
37
+ from TensorFlow.computer_vision.Resnets.resnet_keras import common
38
+ from TensorFlow.computer_vision.Resnets.resnet_keras import resnet_model
39
+ from TensorFlow.computer_vision.Resnets.resnet_keras.common import get_global_batch_size
40
+
41
+
42
+ try:
43
+ import horovod.tensorflow as hvd
44
+ except ImportError:
45
+ hvd = None
46
+ class ResnetRunnable(standard_runnable.StandardTrainable,
47
+ standard_runnable.StandardEvaluable):
48
+ """Implements the training and evaluation APIs for Resnet model."""
49
+
50
+ def __init__(self, flags_obj, time_callback, train_steps, epoch_steps, profiler_callback,mlperf_mlloger,mlperf_mllog):
51
+ standard_runnable.StandardTrainable.__init__(self,
52
+ flags_obj.use_tf_while_loop,
53
+ flags_obj.use_tf_function)
54
+ standard_runnable.StandardEvaluable.__init__(self,
55
+ flags_obj.use_tf_function)
56
+
57
+ self.strategy = tf.distribute.get_strategy()
58
+ self.flags_obj = flags_obj
59
+ self.dtype = flags_core.get_tf_dtype(flags_obj)
60
+ self.time_callback = time_callback
61
+ self.profiler_callback = profiler_callback
62
+ self.first_step = True
63
+ self.warmup_train_dataset = None
64
+ self.warmup_train_iter = None
65
+ self.warmup_eval_dataset = None
66
+ self.warmup_eval_iter = None
67
+
68
+ self.mlperf_mlloger, self.mlperf_mllog = mlperf_mlloger, mlperf_mllog
69
+ # Input pipeline related
70
+ batch_size = flags_obj.batch_size
71
+ if batch_size % self.strategy.num_replicas_in_sync != 0:
72
+ raise ValueError(
73
+ 'Batch size must be divisible by number of replicas : {}'.format(
74
+ self.strategy.num_replicas_in_sync))
75
+
76
+ # As auto rebatching is not supported in
77
+ # `experimental_distribute_datasets_from_function()` API, which is
78
+ # required when cloning dataset to multiple workers in eager mode,
79
+ # we use per-replica batch size.
80
+ self.batch_size = int(batch_size / self.strategy.num_replicas_in_sync)
81
+
82
+ if self.flags_obj.use_synthetic_data:
83
+ self.input_fn = self.get_synth_input_fn(True)
84
+ else:
85
+ self.input_fn = imagenet_preprocessing.input_fn
86
+
87
+ self.model = resnet_model.resnet50(
88
+ num_classes=imagenet_preprocessing.NUM_CLASSES,
89
+ batch_size=flags_obj.batch_size,
90
+ use_l2_regularizer=not flags_obj.single_l2_loss_op)
91
+
92
+ mlperf_variable_map = self.get_mlperf_variable_map()
93
+ for weight in self.model.weights:
94
+ if ('moving_mean' not in weight.name) and ('moving_variance' not in weight.name):
95
+ mlperf_mlloger.event(key=mlperf_mllog.constants.WEIGHTS_INITIALIZATION, metadata={'tensor': mlperf_variable_map[weight.name.split(':')[0]]})
96
+
97
+ self.use_lars_optimizer = self.flags_obj.optimizer == 'LARS'
98
+
99
+ self.optimizer = common.get_optimizer(flags_obj,
100
+ get_global_batch_size(flags_obj.batch_size),
101
+ train_steps,mlperf_mlloger,mlperf_mllog)
102
+ # Make sure iterations variable is created inside scope.
103
+ self.global_step = self.optimizer.iterations
104
+ self.train_steps = train_steps
105
+
106
+ self.one_hot = False
107
+ self.label_smoothing = flags_obj.label_smoothing
108
+ if self.label_smoothing and self.label_smoothing > 0:
109
+ self.one_hot = True
110
+
111
+ use_graph_rewrite = flags_obj.fp16_implementation == 'graph_rewrite'
112
+ if use_graph_rewrite and not flags_obj.use_tf_function:
113
+ raise ValueError('--fp16_implementation=graph_rewrite requires '
114
+ '--use_tf_function to be true')
115
+ self.optimizer = performance.configure_optimizer(
116
+ self.optimizer,
117
+ use_float16=self.dtype == tf.float16,
118
+ use_graph_rewrite=use_graph_rewrite,
119
+ loss_scale=flags_core.get_loss_scale(flags_obj, default_for_fp16=128))
120
+
121
+ if self.flags_obj.report_accuracy_metrics:
122
+ self.train_loss = tf.keras.metrics.Mean('train_loss', dtype=tf.float32)
123
+ if self.one_hot:
124
+ self.train_accuracy = tf.keras.metrics.CategoricalAccuracy(
125
+ 'train_accuracy', dtype=tf.float32)
126
+ else:
127
+ self.train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(
128
+ 'train_accuracy', dtype=tf.float32)
129
+ self.test_loss = tf.keras.metrics.Mean('test_loss', dtype=tf.float32)
130
+ else:
131
+ self.train_loss = None
132
+ self.train_accuracy = None
133
+ self.test_loss = None
134
+
135
+ self.dist_eval = flags_obj.dist_eval
136
+ self.profile = flags_obj.profile
137
+
138
+ if self.one_hot:
139
+ self.test_accuracy = tf.keras.metrics.CategoricalAccuracy(
140
+ 'test_accuracy', dtype=tf.float32)
141
+ else:
142
+ self.test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(
143
+ 'test_accuracy', dtype=tf.float32)
144
+ self.eval_accuracy = 0
145
+
146
+ self.checkpoint = tf.train.Checkpoint(
147
+ model=self.model, optimizer=self.optimizer)
148
+
149
+ self.local_loss_mean = tf.keras.metrics.Mean("local_loss_min", dtype=tf.float32)
150
+
151
+ # Handling epochs.
152
+ self.epoch_steps = epoch_steps
153
+ self.epoch_helper = utils.EpochHelper(epoch_steps, self.global_step)
154
+
155
+ self.num_acc_steps = flags_obj.num_acc_steps
156
+ if self.num_acc_steps > 1:
157
+ self.init_accumulation_variables()
158
+
159
+ self.model_state = None
160
+
161
+ def init_accumulation_variables(self):
162
+ self.cur_acc_step = tf.compat.v1.get_variable(
163
+ name='cur_acc_step',
164
+ shape=(),
165
+ dtype=tf.int32,
166
+ trainable=False,
167
+ initializer=tf.compat.v1.constant_initializer(value=0)
168
+ )
169
+ self.accum_vars = [tf.compat.v1.get_variable(
170
+ name=tvar.name.split(':')[0] + '/accum',
171
+ shape=tvar.shape.as_list(),
172
+ dtype=tf.float32,
173
+ trainable=False,
174
+ initializer=tf.compat.v1.zeros_initializer()) for tvar in self.model.trainable_variables]
175
+ self.loss_acc = tf.compat.v1.get_variable(
176
+ name='loss_acc',
177
+ shape=(),
178
+ dtype=tf.float32,
179
+ trainable=False,
180
+ initializer=tf.compat.v1.constant_initializer(value=0.0)
181
+ )
182
+
183
+ def get_mlperf_variable_map(self):
184
+ try:
185
+ script_path = os.path.realpath(__file__)
186
+ head_tail = os.path.split(script_path)
187
+ mlperf_map_file = head_tail[0] + '/mlperf_variable_map.json'
188
+ with open(mlperf_map_file, mode='r') as file_handle:
189
+ json_content = file_handle.read()
190
+ mlperf_map = json.loads(json_content)
191
+ except IOError:
192
+ raise IOError(f"MLPerf variable map file: {mlperf_map_file} not accesible")
193
+ return mlperf_map
194
+
195
+ def get_synth_input_fn(self, is_training):
196
+ return common.get_synth_input_fn(
197
+ height=imagenet_preprocessing.DEFAULT_IMAGE_SIZE,
198
+ width=imagenet_preprocessing.DEFAULT_IMAGE_SIZE,
199
+ num_channels=imagenet_preprocessing.NUM_CHANNELS,
200
+ num_classes=imagenet_preprocessing.NUM_CLASSES,
201
+ dtype=common.get_dl_type(self.flags_obj),
202
+ drop_remainder=is_training,
203
+ experimental_preloading=self.flags_obj.experimental_preloading)
204
+
205
+ def build_train_dataset(self, synthetic=False, manifest_path=None):
206
+ """See base class."""
207
+ return utils.make_distributed_dataset(
208
+ self.strategy,
209
+ self.input_fn,
210
+ is_training=True,
211
+ data_dir=self.flags_obj.data_dir,
212
+ jpeg_data_dir=self.flags_obj.jpeg_data_dir,
213
+ batch_size=self.batch_size,
214
+ model_dir=self.flags_obj.model_dir,
215
+ parse_record_fn=imagenet_preprocessing.parse_record,
216
+ datasets_num_private_threads=self.flags_obj
217
+ .datasets_num_private_threads,
218
+ dtype=common.get_dl_type(self.flags_obj),
219
+ drop_remainder=True,
220
+ dataset_cache=self.flags_obj.dataset_cache,
221
+ experimental_preloading=self.flags_obj.experimental_preloading,
222
+ num_train_files=self.flags_obj.num_train_files,
223
+ num_eval_files=self.flags_obj.num_eval_files,
224
+ synthetic=synthetic,
225
+ manifest_path=manifest_path)
226
+
227
+ def build_synthetic_train_dataset(self):
228
+ return self.build_train_dataset(synthetic=True)
229
+
230
+ def build_eval_dataset(self, synthetic=False):
231
+ """See base class."""
232
+ return utils.make_distributed_dataset(
233
+ self.strategy,
234
+ self.input_fn,
235
+ is_training=False,
236
+ data_dir=self.flags_obj.data_dir,
237
+ jpeg_data_dir=self.flags_obj.jpeg_data_dir,
238
+ batch_size=self.batch_size,
239
+ model_dir=self.flags_obj.model_dir,
240
+ parse_record_fn=imagenet_preprocessing.parse_record,
241
+ dtype=common.get_dl_type(self.flags_obj),
242
+ dataset_cache=self.flags_obj.dataset_cache,
243
+ experimental_preloading=self.flags_obj.experimental_preloading,
244
+ num_train_files=self.flags_obj.num_train_files,
245
+ num_eval_files=self.flags_obj.num_eval_files,
246
+ synthetic=synthetic)
247
+
248
+ def build_synthetic_eval_dataset(self):
249
+ return self.build_eval_dataset(synthetic=True)
250
+
251
+ def get_prediction_loss(self, labels, logits, training=True):
252
+ if self.one_hot:
253
+ return tf.keras.losses.categorical_crossentropy(
254
+ labels, logits, label_smoothing=self.label_smoothing)
255
+ else:
256
+ return tf.keras.losses.sparse_categorical_crossentropy(labels, logits)
257
+
258
+ def train_loop_begin(self):
259
+ """See base class."""
260
+ # Reset all metrics
261
+ if self.train_loss:
262
+ self.train_loss.reset_states()
263
+ if self.train_accuracy:
264
+ self.train_accuracy.reset_states()
265
+
266
+ self._epoch_begin()
267
+ self.time_callback.on_batch_begin(self.epoch_helper.batch_index)
268
+ if self.profiler_callback is not None:
269
+ self.profiler_callback.on_batch_begin(self.epoch_helper.batch_index)
270
+
271
+ def train_step(self, iterator):
272
+ """See base class."""
273
+
274
+ def step_fn_broadcast():
275
+ if hvd is not None and hvd.is_initialized():
276
+ tf.cond(self.global_step == 1,
277
+ lambda: hvd.broadcast_variables(self.model.variables + self.optimizer.variables(), root_rank=0),
278
+ lambda: tf.constant(True))
279
+
280
+ def step_fn_modeling():
281
+ if self.flags_obj.modeling:
282
+ sess = tf.compat.v1.Session()
283
+ # pbtxt generation
284
+ tf.io.write_graph(sess.graph.as_graph_def(add_shapes=True), self.flags_obj.model_dir, 'graph.pbtxt')
285
+ # meta graph generation
286
+ 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)
287
+
288
+ def step_fn_accumulation_steps_enabled(loss, tape):
289
+ grads = tape.gradient(loss, self.model.trainable_variables)
290
+
291
+ if self.cur_acc_step == 0:
292
+ for i in range(len(self.accum_vars)):
293
+ self.accum_vars[i].assign(grads[i])
294
+ else: # self.cur_acc_step > 0
295
+ for i in range(len(self.accum_vars)):
296
+ self.accum_vars[i].assign_add(grads[i])
297
+
298
+ self.loss_acc.assign_add(loss)
299
+ self.cur_acc_step.assign_add(1)
300
+
301
+ if self.cur_acc_step == self.num_acc_steps:
302
+ grads_and_vars = zip(self.accum_vars, self.model.trainable_variables)
303
+ self.optimizer.apply_gradients(grads_and_vars, experimental_aggregate_gradients=False)
304
+
305
+ step_fn_broadcast()
306
+ step_fn_modeling()
307
+
308
+ if self.train_loss:
309
+ self.train_loss.update_state(self.loss_acc)
310
+
311
+ self.cur_acc_step.assign(0)
312
+ self.loss_acc.assign(0.0)
313
+
314
+ def step_fn_accumulation_steps_disabled(loss, tape):
315
+ if hvd is not None and hvd.is_initialized():
316
+ grads = tape.gradient(loss, self.model.trainable_variables)
317
+ grads_and_vars = zip(grads, self.model.trainable_variables)
318
+ self.optimizer.apply_gradients(grads_and_vars, experimental_aggregate_gradients=False)
319
+ else:
320
+ grad_utils.minimize_using_explicit_allreduce(
321
+ tape, self.optimizer, loss, self.model.trainable_variables)
322
+
323
+ step_fn_broadcast()
324
+ step_fn_modeling()
325
+
326
+ if self.train_loss:
327
+ self.train_loss.update_state(loss)
328
+
329
+ def step_fn(inputs):
330
+ """Function to run on the device."""
331
+ images, labels = inputs
332
+ if self.one_hot:
333
+ labels = tf.cast(labels, tf.int32)
334
+ labels = tf.one_hot(labels, 1001)
335
+ labels = tf.squeeze(labels)
336
+
337
+ with tf.GradientTape() as tape:
338
+ logits = self.model(images, training=True)
339
+ prediction_loss = self.get_prediction_loss(labels, logits)
340
+ loss = tf.reduce_sum(prediction_loss) * (1.0 / self.flags_obj.batch_size)
341
+
342
+ if not self.use_lars_optimizer:
343
+ num_replicas = self.strategy.num_replicas_in_sync
344
+
345
+ if self.flags_obj.single_l2_loss_op:
346
+ l2_loss = self.flags_obj.weight_decay * tf.add_n([
347
+ tf.nn.l2_loss(v)
348
+ for v in self.model.trainable_variables
349
+ if ('bn' not in v.name)
350
+ ])
351
+
352
+ loss += (l2_loss / num_replicas)
353
+ else:
354
+ loss += (tf.reduce_sum(self.model.losses) / num_replicas)
355
+
356
+ loss = loss / self.num_acc_steps
357
+
358
+ if hvd is not None and hvd.is_initialized():
359
+ tape = hvd.DistributedGradientTape(tape)
360
+
361
+ if self.num_acc_steps > 1:
362
+ step_fn_accumulation_steps_enabled(loss, tape)
363
+ else:
364
+ step_fn_accumulation_steps_disabled(loss, tape)
365
+
366
+ if self.train_accuracy:
367
+ self.train_accuracy.update_state(labels, logits)
368
+
369
+ self.strategy.run(step_fn, args=(next(iterator),))
370
+
371
+ def train_loop_end(self):
372
+ """See base class."""
373
+ metrics = dict()
374
+ if self.train_loss:
375
+ metrics['train_loss'] = self.train_loss.result()
376
+ if self.train_accuracy:
377
+ metrics['train_accuracy'] = self.train_accuracy.result()
378
+ self.time_callback.on_batch_end(self.epoch_helper.batch_index - 1)
379
+ if self.profiler_callback is not None:
380
+ self.profiler_callback.on_batch_end(self.epoch_helper.batch_index - 1)
381
+ self._epoch_end()
382
+ return metrics
383
+
384
+ def eval_begin(self):
385
+ """See base class."""
386
+ if self.test_loss:
387
+ self.test_loss.reset_states()
388
+ self.test_accuracy.reset_states()
389
+ epoch_num = int(self.epoch_helper.current_epoch)
390
+ self.mlperf_mlloger.start(
391
+ key=self.mlperf_mllog.constants.EVAL_START, value=None, metadata={'epoch_num': epoch_num + 1})
392
+
393
+ def eval_step(self, iterator):
394
+ """See base class."""
395
+
396
+ def step_fn(inputs):
397
+ """Function to run on the device."""
398
+ images, labels = inputs
399
+ if self.one_hot:
400
+ labels = tf.cast(labels, tf.int32)
401
+ labels = tf.one_hot(labels, 1001)
402
+ labels = tf.squeeze(labels)
403
+
404
+ logits = self.model(images, training=False)
405
+ loss = self.get_prediction_loss(labels, logits, training=False)
406
+ loss = tf.reduce_sum(loss) * (1.0 / self.flags_obj.batch_size)
407
+ if self.test_loss:
408
+ self.test_loss.update_state(loss)
409
+ self.test_accuracy.update_state(labels, logits)
410
+
411
+ self.strategy.run(step_fn, args=(next(iterator),))
412
+
413
+ def eval_end(self):
414
+ """See base class."""
415
+ epoch_num = int(self.epoch_helper.current_epoch)
416
+ self.mlperf_mlloger.end(
417
+ key=self.mlperf_mllog.constants.EVAL_STOP, value=None, metadata={'epoch_num': epoch_num + 1})
418
+
419
+ local_hit = self.test_accuracy.total
420
+ local_count = self.test_accuracy.count
421
+
422
+ global_hit = local_hit
423
+ global_count = local_count
424
+ if hvd is not None and hvd.is_initialized() and self.dist_eval:
425
+ global_hit = hvd.allreduce(local_hit, op=hvd.Sum)
426
+ global_count = hvd.allreduce(local_count, op=hvd.Sum)
427
+ global_accuracy = float(global_hit / global_count)
428
+
429
+ # assign to self
430
+ self.test_accuracy.total.assign(global_hit)
431
+ self.test_accuracy.count.assign(global_count)
432
+
433
+ eval_accuracy = global_accuracy
434
+ self.eval_accuracy = eval_accuracy
435
+ self.mlperf_mlloger.event(
436
+ key=self.mlperf_mllog.constants.EVAL_ACCURACY, value=eval_accuracy, metadata={'epoch_num': epoch_num + 1})
437
+
438
+ first_epoch_num = max(epoch_num - self.flags_obj.epochs_between_evals + 1, 0)
439
+ epoch_count = self.flags_obj.epochs_between_evals
440
+ if first_epoch_num == 0:
441
+ epoch_count = self.flags_obj.eval_offset_epochs
442
+ if epoch_count == 0:
443
+ epoch_count = self.flags_obj.epochs_between_evals
444
+ self.mlperf_mlloger.end(
445
+ key=self.mlperf_mllog.constants.BLOCK_STOP,
446
+ value=None,
447
+ metadata={
448
+ 'first_epoch_num': first_epoch_num + 1,
449
+ 'epoch_count': epoch_count
450
+ })
451
+
452
+ past_threshold = False
453
+ if self.flags_obj.target_accuracy is not None:
454
+ past_threshold = eval_accuracy >= self.flags_obj.target_accuracy
455
+ if (hvd is not None and hvd.is_initialized() and (not self.dist_eval) ):
456
+ past_threshold = hvd.allreduce(tf.cast(past_threshold, tf.float32),
457
+ op=hvd.Sum) > 0
458
+
459
+ continue_training = True
460
+ if past_threshold:
461
+ continue_training = False
462
+ elif ( (not self.profile) and eval_accuracy <= 0.002):
463
+ continue_training = False
464
+ elif self.global_step.numpy() < self.train_steps:
465
+ self.mlperf_mlloger.start(
466
+ key=self.mlperf_mllog.constants.BLOCK_START,
467
+ value=None,
468
+ metadata={
469
+ 'first_epoch_num': epoch_num + 2,
470
+ 'epoch_count': self.flags_obj.epochs_between_evals
471
+ })
472
+
473
+ metrics = {
474
+ 'test_accuracy': eval_accuracy,
475
+ 'continue_training': continue_training,
476
+ }
477
+ if self.test_loss:
478
+ metrics['test_loss'] = self.test_loss.result()
479
+ return metrics
480
+
481
+ def warmup(self, num_steps: Optional[tf.Tensor]) -> Optional[Dict[Text, tf.Tensor]]:
482
+ """Implements device warmup with multiple steps.
483
+
484
+ This loop runs the input pipeline on synthetic data before training, thereby
485
+ allowing tf.function tracing before the dataset is accessed.
486
+
487
+ Args:
488
+ num_steps: A guideline for how many training steps to run. Note that it is
489
+ up to the model what constitutes a "step" (this may involve more than
490
+ one update to model parameters, e.g. if training a GAN).
491
+
492
+ Returns:
493
+ The function may return a dictionary of `Tensors`, which will be
494
+ written to logs and as TensorBoard summaries.
495
+ """
496
+ self.model_state = [weight.numpy() for weight in self.model.weights]
497
+
498
+ if self.warmup_train_dataset is None:
499
+ self.warmup_train_dataset = self.build_synthetic_train_dataset()
500
+ self.warmup_train_iter = tf.nest.map_structure(iter, self.warmup_train_dataset)
501
+
502
+ if self.train_loop_fn is None:
503
+ train_fn = self.train_step
504
+ if self.use_tf_while_loop:
505
+ self.train_loop_fn = utils.create_tf_while_loop_fn(train_fn)
506
+ else:
507
+ if self.use_tf_function:
508
+ train_fn = tf.function(train_fn)
509
+ self.train_loop_fn = utils.create_loop_fn(train_fn)
510
+
511
+ self.train_loop_fn(self.warmup_train_iter, num_steps)
512
+
513
+ if self.warmup_eval_dataset is None:
514
+ self.warmup_eval_dataset = self.build_synthetic_eval_dataset()
515
+ self.warmup_eval_iter = tf.nest.map_structure(iter, self.warmup_eval_dataset)
516
+
517
+ if self.eval_loop_fn is None:
518
+ eval_fn = self.eval_step
519
+ if self.eval_use_tf_function:
520
+ eval_fn = tf.function(eval_fn)
521
+ self.eval_loop_fn = utils.create_loop_fn(eval_fn)
522
+
523
+ self.eval_loop_fn(self.warmup_eval_iter, num_steps)
524
+
525
+ return self.warmup_loop_end()
526
+
527
+ def warmup_loop_end(self):
528
+ """See base class."""
529
+ # Reset the state
530
+ for weight, state in zip(self.model.weights, self.model_state):
531
+ weight.assign(state)
532
+ for weight in self.optimizer.weights:
533
+ weight.assign(tf.zeros(shape=weight.shape, dtype=weight.dtype))
534
+
535
+ def _epoch_begin(self):
536
+ if self.epoch_helper.epoch_begin():
537
+ self.time_callback.on_epoch_begin(self.epoch_helper.current_epoch)
538
+ if self.profiler_callback is not None:
539
+ self.profiler_callback.on_epoch_begin(self.epoch_helper.current_epoch)
540
+
541
+ def _epoch_end(self):
542
+ if self.epoch_helper.epoch_end():
543
+ self.time_callback.on_epoch_end(self.epoch_helper.current_epoch)
544
+ if self.profiler_callback is not None:
545
+ self.profiler_callback.on_epoch_end(self.epoch_helper.current_epoch)
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/utils/__init__.py ADDED
File without changes
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/utils/optimizers/keras/backward_compatibility.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2023 Habana Labs, Ltd. an Intel Company
2
+
3
+ from packaging import version
4
+ import tensorflow as tf
5
+
6
+ if version.parse(tf.__version__) <= version.parse("2.12.0"):
7
+ from tensorflow.python.framework.ops import convert_to_tensor_v2
8
+ else:
9
+ from tensorflow.python.framework.tensor_conversion import convert_to_tensor_v2
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/utils/optimizers/keras/lars_optimizer.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """Layer-wise Adaptive Rate Scaling optimizer for large-batch training."""
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ from __future__ import print_function
20
+
21
+ import tensorflow as tf
22
+ from tensorflow.python.training import training_ops
23
+
24
+
25
+ class LARSOptimizer(tf.keras.optimizers.legacy.Optimizer):
26
+ """Layer-wise Adaptive Rate Scaling for large batch training.
27
+
28
+ Introduced by "Large Batch Training of Convolutional Networks" by Y. You,
29
+ I. Gitman, and B. Ginsburg. (https://arxiv.org/abs/1708.03888)
30
+
31
+ Implements the LARS learning rate scheme presented in the paper above. This
32
+ optimizer is useful when scaling the batch size to up to 32K without
33
+ significant performance degradation. It is recommended to use the optimizer
34
+ in conjunction with:
35
+ - Gradual learning rate warm-up
36
+ - Linear learning rate scaling
37
+ - Poly rule learning rate decay
38
+
39
+ Note, LARS scaling is currently only enabled for dense tensors. Sparse tensors
40
+ use the default momentum optimizer.
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ learning_rate,
46
+ momentum=0.9,
47
+ weight_decay=0.0001,
48
+ # The LARS coefficient is a hyperparameter
49
+ eeta=0.001,
50
+ epsilon=0.0,
51
+ name="LARSOptimizer",
52
+ # Enable skipping variables from LARS scaling.
53
+ # TODO(sameerkm): Enable a direct mechanism to pass a
54
+ # subset of variables to the optimizer.
55
+ skip_list=None,
56
+ use_nesterov=False,
57
+ **kwargs):
58
+ """Construct a new LARS Optimizer.
59
+
60
+ Args:
61
+ learning_rate: A `Tensor`, floating point value, or a schedule that is a
62
+ `tf.keras.optimizers.schedules.LearningRateSchedule`, or a callable
63
+ that takes no arguments and returns the actual value to use. The
64
+ learning rate.
65
+ momentum: A floating point value. Momentum hyperparameter.
66
+ weight_decay: A floating point value. Weight decay hyperparameter.
67
+ eeta: LARS coefficient as used in the paper. Dfault set to LARS
68
+ coefficient from the paper. (eeta / weight_decay) determines the highest
69
+ scaling factor in LARS.
70
+ epsilon: Optional epsilon parameter to be set in models that have very
71
+ small gradients. Default set to 0.0.
72
+ name: Optional name prefix for variables and ops created by LARSOptimizer.
73
+ skip_list: List of strings to enable skipping variables from LARS scaling.
74
+ If any of the strings in skip_list is a subset of var.name, variable
75
+ 'var' is skipped from LARS scaling. For a typical classification model
76
+ with batch normalization, the skip_list is ['batch_normalization',
77
+ 'bias']
78
+ use_nesterov: when set to True, nesterov momentum will be enabled
79
+ **kwargs: keyword arguments.
80
+
81
+ Raises:
82
+ ValueError: If a hyperparameter is set to a non-sensical value.
83
+ """
84
+ if momentum < 0.0:
85
+ raise ValueError("momentum should be positive: %s" % momentum)
86
+ if weight_decay < 0.0:
87
+ raise ValueError("weight_decay should be positive: %s" % weight_decay)
88
+ super(LARSOptimizer, self).__init__(name=name, **kwargs)
89
+
90
+ self._set_hyper("learning_rate", learning_rate)
91
+
92
+ # When directly using class members, instead of
93
+ # _set_hyper and _get_hyper (such as learning_rate above),
94
+ # the values are fixed after __init(), and not being
95
+ # updated during the training process.
96
+ # This provides better performance but less flexibility.
97
+ self.momentum = momentum
98
+ self.weight_decay = weight_decay
99
+ self.eeta = eeta
100
+ self.epsilon = epsilon or tf.keras.backend.epsilon()
101
+ self._skip_list = skip_list
102
+ self.use_nesterov = use_nesterov
103
+
104
+ def _prepare_local(self, var_device, var_dtype, apply_state):
105
+ lr_t = self._get_hyper("learning_rate", var_dtype)
106
+ local_step = tf.cast(self.iterations, var_dtype)
107
+ lr_t = tf.cast(lr_t(local_step), var_dtype)
108
+ learning_rate_t = tf.identity(lr_t)
109
+
110
+ apply_state[(var_device, var_dtype)].update(
111
+ dict(
112
+ learning_rate=learning_rate_t,
113
+ ))
114
+
115
+ def _create_slots(self, var_list):
116
+ for v in var_list:
117
+ self.add_slot(v, "momentum")
118
+
119
+ def compute_lr(self, grad, var, coefficients):
120
+ scaled_lr = coefficients["learning_rate"]
121
+ if self._skip_list is None or not any(v in var.name
122
+ for v in self._skip_list):
123
+ w_norm = tf.norm(var, ord=2)
124
+ g_norm = tf.norm(grad, ord=2)
125
+ trust_ratio = tf.where(
126
+ tf.greater(w_norm, 0),
127
+ tf.where(
128
+ tf.greater(g_norm, 0),
129
+ (self.eeta * w_norm /
130
+ (g_norm + self.weight_decay * w_norm + self.epsilon)), 1.0), 1.0)
131
+
132
+ scaled_lr = coefficients["learning_rate"] * trust_ratio
133
+ # Add the weight regularization gradient
134
+ grad = grad + self.weight_decay * var
135
+ return scaled_lr, grad
136
+
137
+ def _apply_dense(self, grad, var, apply_state=None):
138
+ var_device, var_dtype = var.device, var.dtype.base_dtype
139
+ coefficients = ((apply_state or {}).get((var_device, var_dtype))
140
+ or self._fallback_apply_state(var_device, var_dtype))
141
+
142
+ scaled_lr, grad = self.compute_lr(grad, var, coefficients)
143
+ mom = self.get_slot(var, "momentum")
144
+ return training_ops.apply_momentum(
145
+ var,
146
+ mom,
147
+ tf.cast(1.0, var.dtype.base_dtype),
148
+ grad * scaled_lr,
149
+ self.momentum,
150
+ use_locking=False,
151
+ use_nesterov=self.use_nesterov)
152
+
153
+ def _resource_apply_dense(self, grad, var, apply_state=None):
154
+ var_device, var_dtype = var.device, var.dtype.base_dtype
155
+ coefficients = ((apply_state or {}).get((var_device, var_dtype))
156
+ or self._fallback_apply_state(var_device, var_dtype))
157
+
158
+ scaled_lr, grad = self.compute_lr(grad, var, coefficients)
159
+ mom = self.get_slot(var, "momentum")
160
+
161
+ # ============================================================
162
+ return training_ops.resource_apply_keras_momentum(
163
+ var.handle,
164
+ mom.handle,
165
+ scaled_lr,
166
+ grad,
167
+ self.momentum,
168
+ use_locking=False,
169
+ use_nesterov=self.use_nesterov)
170
+ # ============================================================
171
+
172
+ # ============================================================
173
+ # mom_t = mom * self.momentum - grad * scaled_lr
174
+ # mom_t = state_ops.assign(mom, mom_t, use_locking=False)
175
+ # if self.use_nesterov:
176
+ # var_t = var + mom_t * self.momentum - grad * scaled_lr
177
+ # else:
178
+ # var_t = var + mom_t
179
+ # return state_ops.assign(var, var_t, use_locking=False).op
180
+ # ============================================================
181
+
182
+ # Fallback to momentum optimizer for sparse tensors
183
+ def _apply_sparse(self, grad, var, apply_state=None):
184
+ var_device, var_dtype = var.device, var.dtype.base_dtype
185
+ coefficients = ((apply_state or {}).get((var_device, var_dtype))
186
+ or self._fallback_apply_state(var_device, var_dtype))
187
+
188
+ mom = self.get_slot(var, "momentum")
189
+ return training_ops.sparse_apply_momentum(
190
+ var,
191
+ mom,
192
+ coefficients["learning_rate"],
193
+ grad.values,
194
+ grad.indices,
195
+ self.momentum,
196
+ use_locking=False,
197
+ use_nesterov=self.use_nesterov)
198
+
199
+ def _resource_apply_sparse(self, grad, var, indices, apply_state=None):
200
+ var_device, var_dtype = var.device, var.dtype.base_dtype
201
+ coefficients = ((apply_state or {}).get((var_device, var_dtype))
202
+ or self._fallback_apply_state(var_device, var_dtype))
203
+
204
+ mom = self.get_slot(var, "momentum")
205
+ return training_ops.resource_sparse_apply_keras_momentum(
206
+ var.handle,
207
+ mom.handle,
208
+ coefficients["learning_rate"],
209
+ grad,
210
+ indices,
211
+ self.momentum,
212
+ use_locking=False,
213
+ use_nesterov=self.use_nesterov)
214
+
215
+ def get_config(self):
216
+ config = super(LARSOptimizer, self).get_config()
217
+ config.update({
218
+ "learning_rate": self._serialize_hyperparameter("learning_rate"),
219
+ "momentum": self.momentum,
220
+ "weight_decay": self.weight_decay,
221
+ "eeta": self.eeta,
222
+ "epsilon": self.epsilon,
223
+ "use_nesterov": self.use_nesterov,
224
+ })
225
+ return config
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/Resnets/utils/optimizers/keras/lars_util.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ # Copyright (C) 2023 Habana Labs, Ltd. an Intel Company
16
+ # ==============================================================================
17
+ """Enable Layer-wise Adaptive Rate Scaling optimizer in ResNet."""
18
+
19
+ from __future__ import absolute_import
20
+ from __future__ import division
21
+ from __future__ import print_function
22
+
23
+ from absl import flags
24
+ import tensorflow as tf
25
+ from TensorFlow.computer_vision.Resnets.utils.optimizers.keras import backward_compatibility
26
+
27
+ from tensorflow.python.eager import context
28
+ from tensorflow.python.framework import ops
29
+ from tensorflow.python.ops import math_ops
30
+ FLAGS = flags.FLAGS
31
+
32
+
33
+ def define_lars_flags():
34
+ """Defines flags needed by LARS optimizer."""
35
+
36
+ flags.DEFINE_float(
37
+ 'end_learning_rate',
38
+ default=None,
39
+ help=('Polynomial decay end learning rate.'))
40
+
41
+ flags.DEFINE_float(
42
+ 'lars_epsilon', default=0.0, help=('Override autoselected LARS epsilon.'))
43
+
44
+ flags.DEFINE_float(
45
+ 'warmup_epochs',
46
+ default=None,
47
+ help=('Override autoselected polynomial decay warmup epochs.'))
48
+
49
+ flags.DEFINE_float(
50
+ 'momentum',
51
+ default=0.9,
52
+ help=('Momentum parameter used in the MomentumOptimizer.'))
53
+
54
+ flags.DEFINE_float(
55
+ 'lars_decay_epochs',
56
+ default=None,
57
+ help=('Momentum parameter used in the MomentumOptimizer.'))
58
+
59
+
60
+ class PolynomialDecayWithWarmup(
61
+ tf.keras.optimizers.schedules.LearningRateSchedule):
62
+ """A LearningRateSchedule that uses a polynomial decay with warmup."""
63
+
64
+ def __init__(self,
65
+ batch_size,
66
+ steps_per_epoch,
67
+ train_steps,
68
+ initial_learning_rate=None,
69
+ end_learning_rate=None,
70
+ warmup_epochs=None,
71
+ compute_lr_on_cpu=False,
72
+ name=None,
73
+ mlperf_mlloger=None,
74
+ mlperf_mllog=None):
75
+ """Applies a polynomial decay to the learning rate with warmup."""
76
+ super(PolynomialDecayWithWarmup, self).__init__()
77
+
78
+ self.batch_size = batch_size
79
+ self.steps_per_epoch = steps_per_epoch
80
+ self.train_steps = train_steps
81
+ self.name = name
82
+ self.learning_rate_ops_cache = {}
83
+ self.compute_lr_on_cpu = compute_lr_on_cpu
84
+
85
+ if batch_size < 16384:
86
+ self.initial_learning_rate = 10.0
87
+ warmup_epochs_ = 5
88
+ elif batch_size < 32768:
89
+ self.initial_learning_rate = 25.0
90
+ warmup_epochs_ = 5
91
+ else:
92
+ self.initial_learning_rate = 31.2
93
+ warmup_epochs_ = 25
94
+
95
+ # Override default poly learning rate and warmup epochs
96
+ if initial_learning_rate:
97
+ self.initial_learning_rate = initial_learning_rate
98
+
99
+ if end_learning_rate:
100
+ self.end_learning_rate = end_learning_rate
101
+ else:
102
+ self.end_learning_rate = 0.0001
103
+
104
+ if warmup_epochs is not None:
105
+ warmup_epochs_ = warmup_epochs
106
+ self.warmup_epochs = warmup_epochs_
107
+
108
+ opt_name = FLAGS.optimizer.lower()
109
+ mlperf_mlloger.event(key=mlperf_mllog.constants.OPT_NAME, value=opt_name)
110
+
111
+ warmup_steps = warmup_epochs_ * steps_per_epoch
112
+ self.warmup_steps = tf.cast(warmup_steps, tf.float32)
113
+ if (FLAGS.lars_decay_epochs is None):
114
+ self.decay_steps = train_steps
115
+ else:
116
+ self.decay_steps = FLAGS.lars_decay_epochs * steps_per_epoch
117
+ self.decay_steps = self.decay_steps - warmup_steps + 1
118
+
119
+ if opt_name == 'lars':
120
+ mlperf_mlloger.event(key=mlperf_mllog.constants.LARS_EPSILON, value=FLAGS.lars_epsilon)
121
+ mlperf_mlloger.event(key=mlperf_mllog.constants.LARS_OPT_WEIGHT_DECAY, value=FLAGS.weight_decay)
122
+ mlperf_mlloger.event(key=mlperf_mllog.constants.LARS_OPT_END_LR, value=self.end_learning_rate)
123
+ mlperf_mlloger.event(key=mlperf_mllog.constants.LARS_OPT_LR_DECAY_STEPS, value=int(self.decay_steps))
124
+ mlperf_mlloger.event(key=mlperf_mllog.constants.LARS_OPT_LR_DECAY_POLY_POWER, value=2.0)
125
+ mlperf_mlloger.event(key='lars_opt_momentum', value=FLAGS.momentum)
126
+ elif opt_name == 'sgd':
127
+ mlperf_mlloger.event(key=mlperf_mllog.constants.OPT_WEIGHT_DECAY, value=FLAGS.weight_decay)
128
+ mlperf_mlloger.event(key='opt_momentum', value=FLAGS.momentum)
129
+ else:
130
+ print('NOT Supported')
131
+ mlperf_mlloger.event(key=opt_name+'_'+mlperf_mllog.constants.OPT_LR_WARMUP_EPOCHS, value=warmup_epochs_)
132
+ mlperf_mlloger.event(key=opt_name+'_'+mlperf_mllog.constants.OPT_BASE_LR, value=self.initial_learning_rate)
133
+
134
+ self.poly_rate_scheduler = tf.keras.optimizers.schedules.PolynomialDecay(
135
+ initial_learning_rate=self.initial_learning_rate,
136
+ decay_steps=self.decay_steps,
137
+ end_learning_rate=self.end_learning_rate,
138
+ power=2.0)
139
+
140
+ def __call__(self, step):
141
+ if tf.executing_eagerly():
142
+ return self._get_learning_rate(step)
143
+
144
+ # In an eager function or graph, the current implementation of optimizer
145
+ # repeatedly call and thus create ops for the learning rate schedule. To
146
+ # avoid this, we cache the ops if not executing eagerly.
147
+ graph = tf.compat.v1.get_default_graph()
148
+ if graph not in self.learning_rate_ops_cache:
149
+ if self.compute_lr_on_cpu:
150
+ with tf.device('/device:CPU:0'):
151
+ self.learning_rate_ops_cache[graph] = self._get_learning_rate(step)
152
+ else:
153
+ self.learning_rate_ops_cache[graph] = self._get_learning_rate(step)
154
+ return self.learning_rate_ops_cache[graph]
155
+
156
+ def _get_learning_rate(self, step):
157
+ with ops.name_scope_v2(self.name or 'PolynomialDecayWithWarmup') as name:
158
+
159
+ initial_learning_rate = backward_compatibility.convert_to_tensor_v2(
160
+ self.initial_learning_rate, name='initial_learning_rate')
161
+ warmup_steps = backward_compatibility.convert_to_tensor_v2(
162
+ self.warmup_steps, name='warmup_steps')
163
+
164
+ warmup_rate = (
165
+ initial_learning_rate * step / warmup_steps)
166
+
167
+ poly_steps = math_ops.maximum(math_ops.subtract(step, warmup_steps), 1)
168
+ poly_rate = self.poly_rate_scheduler(poly_steps)
169
+
170
+ decay_rate = tf.where(step <= warmup_steps,
171
+ warmup_rate, poly_rate, name=name)
172
+ return decay_rate
173
+
174
+ def get_config(self):
175
+ return {
176
+ 'batch_size': self.batch_size,
177
+ 'steps_per_epoch': self.steps_per_epoch,
178
+ 'train_steps': self.train_steps,
179
+ 'initial_learning_rate': self.initial_learning_rate,
180
+ 'end_learning_rate': self.end_learning_rate,
181
+ 'warmup_epochs': self.warmup_epochs,
182
+ 'name': self.name,
183
+ }
docker/intel_code/llama13b/Model-References/MLPERF3.1/Training/benchmarks/resnet/implementations/TensorFlow/computer_vision/__init__.py ADDED
File without changes