easy-cs-rec-custommodel 0.8.6__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of easy-cs-rec-custommodel might be problematic. Click here for more details.

Files changed (336) hide show
  1. easy_cs_rec_custommodel-0.8.6.dist-info/LICENSE +203 -0
  2. easy_cs_rec_custommodel-0.8.6.dist-info/METADATA +48 -0
  3. easy_cs_rec_custommodel-0.8.6.dist-info/RECORD +336 -0
  4. easy_cs_rec_custommodel-0.8.6.dist-info/WHEEL +6 -0
  5. easy_cs_rec_custommodel-0.8.6.dist-info/top_level.txt +2 -0
  6. easy_rec/__init__.py +114 -0
  7. easy_rec/python/__init__.py +0 -0
  8. easy_rec/python/builders/__init__.py +0 -0
  9. easy_rec/python/builders/hyperparams_builder.py +78 -0
  10. easy_rec/python/builders/loss_builder.py +333 -0
  11. easy_rec/python/builders/optimizer_builder.py +211 -0
  12. easy_rec/python/builders/strategy_builder.py +44 -0
  13. easy_rec/python/compat/__init__.py +0 -0
  14. easy_rec/python/compat/adam_s.py +245 -0
  15. easy_rec/python/compat/array_ops.py +229 -0
  16. easy_rec/python/compat/dynamic_variable.py +542 -0
  17. easy_rec/python/compat/early_stopping.py +653 -0
  18. easy_rec/python/compat/embedding_ops.py +162 -0
  19. easy_rec/python/compat/embedding_parallel_saver.py +316 -0
  20. easy_rec/python/compat/estimator_train.py +116 -0
  21. easy_rec/python/compat/exporter.py +473 -0
  22. easy_rec/python/compat/feature_column/__init__.py +0 -0
  23. easy_rec/python/compat/feature_column/feature_column.py +3675 -0
  24. easy_rec/python/compat/feature_column/feature_column_v2.py +5233 -0
  25. easy_rec/python/compat/feature_column/sequence_feature_column.py +648 -0
  26. easy_rec/python/compat/feature_column/utils.py +154 -0
  27. easy_rec/python/compat/layers.py +329 -0
  28. easy_rec/python/compat/ops.py +14 -0
  29. easy_rec/python/compat/optimizers.py +619 -0
  30. easy_rec/python/compat/queues.py +311 -0
  31. easy_rec/python/compat/regularizers.py +208 -0
  32. easy_rec/python/compat/sok_optimizer.py +440 -0
  33. easy_rec/python/compat/sync_replicas_optimizer.py +528 -0
  34. easy_rec/python/compat/weight_decay_optimizers.py +475 -0
  35. easy_rec/python/core/__init__.py +0 -0
  36. easy_rec/python/core/easyrec_metrics/__init__.py +24 -0
  37. easy_rec/python/core/easyrec_metrics/distribute_metrics_impl_pai.py +3702 -0
  38. easy_rec/python/core/easyrec_metrics/distribute_metrics_impl_tf.py +3768 -0
  39. easy_rec/python/core/learning_schedules.py +228 -0
  40. easy_rec/python/core/metrics.py +402 -0
  41. easy_rec/python/core/sampler.py +844 -0
  42. easy_rec/python/eval.py +102 -0
  43. easy_rec/python/export.py +150 -0
  44. easy_rec/python/feature_column/__init__.py +0 -0
  45. easy_rec/python/feature_column/feature_column.py +664 -0
  46. easy_rec/python/feature_column/feature_group.py +89 -0
  47. easy_rec/python/hpo/__init__.py +0 -0
  48. easy_rec/python/hpo/emr_hpo.py +140 -0
  49. easy_rec/python/hpo/generate_hpo_sql.py +71 -0
  50. easy_rec/python/hpo/pai_hpo.py +297 -0
  51. easy_rec/python/inference/__init__.py +0 -0
  52. easy_rec/python/inference/csv_predictor.py +189 -0
  53. easy_rec/python/inference/hive_parquet_predictor.py +200 -0
  54. easy_rec/python/inference/hive_predictor.py +166 -0
  55. easy_rec/python/inference/odps_predictor.py +70 -0
  56. easy_rec/python/inference/parquet_predictor.py +147 -0
  57. easy_rec/python/inference/parquet_predictor_v2.py +147 -0
  58. easy_rec/python/inference/predictor.py +621 -0
  59. easy_rec/python/inference/processor/__init__.py +0 -0
  60. easy_rec/python/inference/processor/test.py +170 -0
  61. easy_rec/python/inference/vector_retrieve.py +124 -0
  62. easy_rec/python/input/__init__.py +0 -0
  63. easy_rec/python/input/batch_tfrecord_input.py +117 -0
  64. easy_rec/python/input/criteo_binary_reader.py +259 -0
  65. easy_rec/python/input/criteo_input.py +107 -0
  66. easy_rec/python/input/csv_input.py +175 -0
  67. easy_rec/python/input/csv_input_ex.py +72 -0
  68. easy_rec/python/input/csv_input_v2.py +68 -0
  69. easy_rec/python/input/datahub_input.py +320 -0
  70. easy_rec/python/input/dummy_input.py +58 -0
  71. easy_rec/python/input/hive_input.py +123 -0
  72. easy_rec/python/input/hive_parquet_input.py +140 -0
  73. easy_rec/python/input/hive_rtp_input.py +174 -0
  74. easy_rec/python/input/input.py +1064 -0
  75. easy_rec/python/input/kafka_dataset.py +144 -0
  76. easy_rec/python/input/kafka_input.py +235 -0
  77. easy_rec/python/input/load_parquet.py +317 -0
  78. easy_rec/python/input/odps_input.py +101 -0
  79. easy_rec/python/input/odps_input_v2.py +110 -0
  80. easy_rec/python/input/odps_input_v3.py +132 -0
  81. easy_rec/python/input/odps_rtp_input.py +187 -0
  82. easy_rec/python/input/odps_rtp_input_v2.py +104 -0
  83. easy_rec/python/input/parquet_input.py +397 -0
  84. easy_rec/python/input/parquet_input_v2.py +180 -0
  85. easy_rec/python/input/parquet_input_v3.py +203 -0
  86. easy_rec/python/input/rtp_input.py +225 -0
  87. easy_rec/python/input/rtp_input_v2.py +145 -0
  88. easy_rec/python/input/tfrecord_input.py +100 -0
  89. easy_rec/python/layers/__init__.py +0 -0
  90. easy_rec/python/layers/backbone.py +571 -0
  91. easy_rec/python/layers/capsule_layer.py +176 -0
  92. easy_rec/python/layers/cmbf.py +390 -0
  93. easy_rec/python/layers/common_layers.py +192 -0
  94. easy_rec/python/layers/dnn.py +87 -0
  95. easy_rec/python/layers/embed_input_layer.py +25 -0
  96. easy_rec/python/layers/fm.py +26 -0
  97. easy_rec/python/layers/input_layer.py +396 -0
  98. easy_rec/python/layers/keras/__init__.py +34 -0
  99. easy_rec/python/layers/keras/activation.py +114 -0
  100. easy_rec/python/layers/keras/attention.py +267 -0
  101. easy_rec/python/layers/keras/auxiliary_loss.py +47 -0
  102. easy_rec/python/layers/keras/blocks.py +262 -0
  103. easy_rec/python/layers/keras/bst.py +119 -0
  104. easy_rec/python/layers/keras/custom_ops.py +250 -0
  105. easy_rec/python/layers/keras/data_augment.py +133 -0
  106. easy_rec/python/layers/keras/din.py +67 -0
  107. easy_rec/python/layers/keras/einsum_dense.py +598 -0
  108. easy_rec/python/layers/keras/embedding.py +81 -0
  109. easy_rec/python/layers/keras/fibinet.py +251 -0
  110. easy_rec/python/layers/keras/interaction.py +416 -0
  111. easy_rec/python/layers/keras/layer_norm.py +364 -0
  112. easy_rec/python/layers/keras/mask_net.py +166 -0
  113. easy_rec/python/layers/keras/multi_head_attention.py +717 -0
  114. easy_rec/python/layers/keras/multi_task.py +125 -0
  115. easy_rec/python/layers/keras/numerical_embedding.py +376 -0
  116. easy_rec/python/layers/keras/ppnet.py +194 -0
  117. easy_rec/python/layers/keras/transformer.py +192 -0
  118. easy_rec/python/layers/layer_norm.py +51 -0
  119. easy_rec/python/layers/mmoe.py +83 -0
  120. easy_rec/python/layers/multihead_attention.py +162 -0
  121. easy_rec/python/layers/multihead_cross_attention.py +749 -0
  122. easy_rec/python/layers/senet.py +73 -0
  123. easy_rec/python/layers/seq_input_layer.py +134 -0
  124. easy_rec/python/layers/sequence_feature_layer.py +249 -0
  125. easy_rec/python/layers/uniter.py +301 -0
  126. easy_rec/python/layers/utils.py +248 -0
  127. easy_rec/python/layers/variational_dropout_layer.py +130 -0
  128. easy_rec/python/loss/__init__.py +0 -0
  129. easy_rec/python/loss/circle_loss.py +82 -0
  130. easy_rec/python/loss/contrastive_loss.py +79 -0
  131. easy_rec/python/loss/f1_reweight_loss.py +38 -0
  132. easy_rec/python/loss/focal_loss.py +93 -0
  133. easy_rec/python/loss/jrc_loss.py +128 -0
  134. easy_rec/python/loss/listwise_loss.py +161 -0
  135. easy_rec/python/loss/multi_similarity.py +68 -0
  136. easy_rec/python/loss/pairwise_loss.py +307 -0
  137. easy_rec/python/loss/softmax_loss_with_negative_mining.py +110 -0
  138. easy_rec/python/loss/zero_inflated_lognormal.py +76 -0
  139. easy_rec/python/main.py +878 -0
  140. easy_rec/python/model/__init__.py +0 -0
  141. easy_rec/python/model/autoint.py +73 -0
  142. easy_rec/python/model/cmbf.py +47 -0
  143. easy_rec/python/model/collaborative_metric_learning.py +182 -0
  144. easy_rec/python/model/custom_model.py +323 -0
  145. easy_rec/python/model/dat.py +138 -0
  146. easy_rec/python/model/dbmtl.py +116 -0
  147. easy_rec/python/model/dcn.py +70 -0
  148. easy_rec/python/model/deepfm.py +106 -0
  149. easy_rec/python/model/dlrm.py +73 -0
  150. easy_rec/python/model/dropoutnet.py +207 -0
  151. easy_rec/python/model/dssm.py +154 -0
  152. easy_rec/python/model/dssm_senet.py +143 -0
  153. easy_rec/python/model/dummy_model.py +48 -0
  154. easy_rec/python/model/easy_rec_estimator.py +739 -0
  155. easy_rec/python/model/easy_rec_model.py +467 -0
  156. easy_rec/python/model/esmm.py +242 -0
  157. easy_rec/python/model/fm.py +63 -0
  158. easy_rec/python/model/match_model.py +357 -0
  159. easy_rec/python/model/mind.py +445 -0
  160. easy_rec/python/model/mmoe.py +70 -0
  161. easy_rec/python/model/multi_task_model.py +303 -0
  162. easy_rec/python/model/multi_tower.py +62 -0
  163. easy_rec/python/model/multi_tower_bst.py +190 -0
  164. easy_rec/python/model/multi_tower_din.py +130 -0
  165. easy_rec/python/model/multi_tower_recall.py +68 -0
  166. easy_rec/python/model/pdn.py +203 -0
  167. easy_rec/python/model/ple.py +120 -0
  168. easy_rec/python/model/rank_model.py +485 -0
  169. easy_rec/python/model/rocket_launching.py +203 -0
  170. easy_rec/python/model/simple_multi_task.py +54 -0
  171. easy_rec/python/model/uniter.py +46 -0
  172. easy_rec/python/model/wide_and_deep.py +121 -0
  173. easy_rec/python/ops/1.12/incr_record.so +0 -0
  174. easy_rec/python/ops/1.12/kafka.so +0 -0
  175. easy_rec/python/ops/1.12/libcustom_ops.so +0 -0
  176. easy_rec/python/ops/1.12/libembed_op.so +0 -0
  177. easy_rec/python/ops/1.12/libhiredis.so.1.0.0 +0 -0
  178. easy_rec/python/ops/1.12/librdkafka++.so.1 +0 -0
  179. easy_rec/python/ops/1.12/librdkafka.so.1 +0 -0
  180. easy_rec/python/ops/1.12/libredis++.so +0 -0
  181. easy_rec/python/ops/1.12/libredis++.so.1 +0 -0
  182. easy_rec/python/ops/1.12/libredis++.so.1.2.3 +0 -0
  183. easy_rec/python/ops/1.12/libstr_avx_op.so +0 -0
  184. easy_rec/python/ops/1.12/libwrite_sparse_kv.so +0 -0
  185. easy_rec/python/ops/1.15/incr_record.so +0 -0
  186. easy_rec/python/ops/1.15/kafka.so +0 -0
  187. easy_rec/python/ops/1.15/libcustom_ops.so +0 -0
  188. easy_rec/python/ops/1.15/libembed_op.so +0 -0
  189. easy_rec/python/ops/1.15/libhiredis.so.1.0.0 +0 -0
  190. easy_rec/python/ops/1.15/librdkafka++.so +0 -0
  191. easy_rec/python/ops/1.15/librdkafka++.so.1 +0 -0
  192. easy_rec/python/ops/1.15/librdkafka.so +0 -0
  193. easy_rec/python/ops/1.15/librdkafka.so.1 +0 -0
  194. easy_rec/python/ops/1.15/libredis++.so.1 +0 -0
  195. easy_rec/python/ops/1.15/libstr_avx_op.so +0 -0
  196. easy_rec/python/ops/2.12/libcustom_ops.so +0 -0
  197. easy_rec/python/ops/2.12/libload_embed.so +0 -0
  198. easy_rec/python/ops/2.12/libstr_avx_op.so +0 -0
  199. easy_rec/python/ops/__init__.py +0 -0
  200. easy_rec/python/ops/gen_kafka_ops.py +193 -0
  201. easy_rec/python/ops/gen_str_avx_op.py +28 -0
  202. easy_rec/python/ops/incr_record.py +30 -0
  203. easy_rec/python/predict.py +170 -0
  204. easy_rec/python/protos/__init__.py +0 -0
  205. easy_rec/python/protos/autoint_pb2.py +122 -0
  206. easy_rec/python/protos/backbone_pb2.py +1416 -0
  207. easy_rec/python/protos/cmbf_pb2.py +435 -0
  208. easy_rec/python/protos/collaborative_metric_learning_pb2.py +252 -0
  209. easy_rec/python/protos/custom_model_pb2.py +57 -0
  210. easy_rec/python/protos/dat_pb2.py +262 -0
  211. easy_rec/python/protos/data_source_pb2.py +422 -0
  212. easy_rec/python/protos/dataset_pb2.py +1920 -0
  213. easy_rec/python/protos/dbmtl_pb2.py +191 -0
  214. easy_rec/python/protos/dcn_pb2.py +197 -0
  215. easy_rec/python/protos/deepfm_pb2.py +163 -0
  216. easy_rec/python/protos/dlrm_pb2.py +163 -0
  217. easy_rec/python/protos/dnn_pb2.py +329 -0
  218. easy_rec/python/protos/dropoutnet_pb2.py +239 -0
  219. easy_rec/python/protos/dssm_pb2.py +262 -0
  220. easy_rec/python/protos/dssm_senet_pb2.py +282 -0
  221. easy_rec/python/protos/easy_rec_model_pb2.py +1672 -0
  222. easy_rec/python/protos/esmm_pb2.py +133 -0
  223. easy_rec/python/protos/eval_pb2.py +930 -0
  224. easy_rec/python/protos/export_pb2.py +379 -0
  225. easy_rec/python/protos/feature_config_pb2.py +1359 -0
  226. easy_rec/python/protos/fm_pb2.py +90 -0
  227. easy_rec/python/protos/hive_config_pb2.py +138 -0
  228. easy_rec/python/protos/hyperparams_pb2.py +624 -0
  229. easy_rec/python/protos/keras_layer_pb2.py +692 -0
  230. easy_rec/python/protos/layer_pb2.py +1936 -0
  231. easy_rec/python/protos/loss_pb2.py +1713 -0
  232. easy_rec/python/protos/mind_pb2.py +497 -0
  233. easy_rec/python/protos/mmoe_pb2.py +215 -0
  234. easy_rec/python/protos/multi_tower_pb2.py +295 -0
  235. easy_rec/python/protos/multi_tower_recall_pb2.py +198 -0
  236. easy_rec/python/protos/optimizer_pb2.py +2017 -0
  237. easy_rec/python/protos/pdn_pb2.py +293 -0
  238. easy_rec/python/protos/pipeline_pb2.py +516 -0
  239. easy_rec/python/protos/ple_pb2.py +231 -0
  240. easy_rec/python/protos/predict_pb2.py +1140 -0
  241. easy_rec/python/protos/rocket_launching_pb2.py +169 -0
  242. easy_rec/python/protos/seq_encoder_pb2.py +1084 -0
  243. easy_rec/python/protos/simi_pb2.py +54 -0
  244. easy_rec/python/protos/simple_multi_task_pb2.py +97 -0
  245. easy_rec/python/protos/tf_predict_pb2.py +630 -0
  246. easy_rec/python/protos/tower_pb2.py +661 -0
  247. easy_rec/python/protos/train_pb2.py +1197 -0
  248. easy_rec/python/protos/uniter_pb2.py +307 -0
  249. easy_rec/python/protos/variational_dropout_pb2.py +91 -0
  250. easy_rec/python/protos/wide_and_deep_pb2.py +131 -0
  251. easy_rec/python/test/__init__.py +0 -0
  252. easy_rec/python/test/csv_input_test.py +340 -0
  253. easy_rec/python/test/custom_early_stop_func.py +19 -0
  254. easy_rec/python/test/dh_local_run.py +104 -0
  255. easy_rec/python/test/embed_test.py +155 -0
  256. easy_rec/python/test/emr_run.py +119 -0
  257. easy_rec/python/test/eval_metric_test.py +107 -0
  258. easy_rec/python/test/excel_convert_test.py +64 -0
  259. easy_rec/python/test/export_test.py +513 -0
  260. easy_rec/python/test/fg_test.py +70 -0
  261. easy_rec/python/test/hive_input_test.py +311 -0
  262. easy_rec/python/test/hpo_test.py +235 -0
  263. easy_rec/python/test/kafka_test.py +373 -0
  264. easy_rec/python/test/local_incr_test.py +122 -0
  265. easy_rec/python/test/loss_test.py +110 -0
  266. easy_rec/python/test/odps_command.py +61 -0
  267. easy_rec/python/test/odps_local_run.py +86 -0
  268. easy_rec/python/test/odps_run.py +254 -0
  269. easy_rec/python/test/odps_test_cls.py +39 -0
  270. easy_rec/python/test/odps_test_prepare.py +198 -0
  271. easy_rec/python/test/odps_test_util.py +237 -0
  272. easy_rec/python/test/pre_check_test.py +54 -0
  273. easy_rec/python/test/predictor_test.py +394 -0
  274. easy_rec/python/test/rtp_convert_test.py +133 -0
  275. easy_rec/python/test/run.py +138 -0
  276. easy_rec/python/test/train_eval_test.py +1299 -0
  277. easy_rec/python/test/util_test.py +85 -0
  278. easy_rec/python/test/zero_inflated_lognormal_test.py +53 -0
  279. easy_rec/python/tools/__init__.py +0 -0
  280. easy_rec/python/tools/add_boundaries_to_config.py +67 -0
  281. easy_rec/python/tools/add_feature_info_to_config.py +145 -0
  282. easy_rec/python/tools/convert_config_format.py +48 -0
  283. easy_rec/python/tools/convert_rtp_data.py +79 -0
  284. easy_rec/python/tools/convert_rtp_fg.py +106 -0
  285. easy_rec/python/tools/create_config_from_excel.py +427 -0
  286. easy_rec/python/tools/criteo/__init__.py +0 -0
  287. easy_rec/python/tools/criteo/convert_data.py +157 -0
  288. easy_rec/python/tools/edit_lookup_graph.py +134 -0
  289. easy_rec/python/tools/faiss_index_pai.py +116 -0
  290. easy_rec/python/tools/feature_selection.py +316 -0
  291. easy_rec/python/tools/hit_rate_ds.py +223 -0
  292. easy_rec/python/tools/hit_rate_pai.py +138 -0
  293. easy_rec/python/tools/pre_check.py +120 -0
  294. easy_rec/python/tools/predict_and_chk.py +111 -0
  295. easy_rec/python/tools/read_kafka.py +55 -0
  296. easy_rec/python/tools/split_model_pai.py +286 -0
  297. easy_rec/python/tools/split_pdn_model_pai.py +272 -0
  298. easy_rec/python/tools/test_saved_model.py +80 -0
  299. easy_rec/python/tools/view_saved_model.py +39 -0
  300. easy_rec/python/tools/write_kafka.py +65 -0
  301. easy_rec/python/train_eval.py +325 -0
  302. easy_rec/python/utils/__init__.py +15 -0
  303. easy_rec/python/utils/activation.py +120 -0
  304. easy_rec/python/utils/check_utils.py +87 -0
  305. easy_rec/python/utils/compat.py +14 -0
  306. easy_rec/python/utils/config_util.py +652 -0
  307. easy_rec/python/utils/constant.py +43 -0
  308. easy_rec/python/utils/convert_rtp_fg.py +616 -0
  309. easy_rec/python/utils/dag.py +192 -0
  310. easy_rec/python/utils/distribution_utils.py +268 -0
  311. easy_rec/python/utils/ds_util.py +65 -0
  312. easy_rec/python/utils/embedding_utils.py +73 -0
  313. easy_rec/python/utils/estimator_utils.py +1036 -0
  314. easy_rec/python/utils/export_big_model.py +630 -0
  315. easy_rec/python/utils/expr_util.py +118 -0
  316. easy_rec/python/utils/fg_util.py +53 -0
  317. easy_rec/python/utils/hit_rate_utils.py +220 -0
  318. easy_rec/python/utils/hive_utils.py +183 -0
  319. easy_rec/python/utils/hpo_util.py +137 -0
  320. easy_rec/python/utils/hvd_utils.py +56 -0
  321. easy_rec/python/utils/input_utils.py +108 -0
  322. easy_rec/python/utils/io_util.py +282 -0
  323. easy_rec/python/utils/load_class.py +249 -0
  324. easy_rec/python/utils/meta_graph_editor.py +941 -0
  325. easy_rec/python/utils/multi_optimizer.py +62 -0
  326. easy_rec/python/utils/numpy_utils.py +18 -0
  327. easy_rec/python/utils/odps_util.py +79 -0
  328. easy_rec/python/utils/pai_util.py +86 -0
  329. easy_rec/python/utils/proto_util.py +90 -0
  330. easy_rec/python/utils/restore_filter.py +89 -0
  331. easy_rec/python/utils/shape_utils.py +432 -0
  332. easy_rec/python/utils/static_shape.py +71 -0
  333. easy_rec/python/utils/test_utils.py +866 -0
  334. easy_rec/python/utils/tf_utils.py +56 -0
  335. easy_rec/version.py +4 -0
  336. test/__init__.py +0 -0
@@ -0,0 +1,653 @@
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
+ """Utilities for early stopping."""
16
+
17
+ import collections
18
+ import datetime
19
+ import logging
20
+ import operator
21
+ import os
22
+ import threading
23
+ import time
24
+
25
+ import tensorflow as tf
26
+ from distutils.version import LooseVersion
27
+ from tensorflow.python.framework import dtypes
28
+ from tensorflow.python.framework import ops
29
+ from tensorflow.python.ops import init_ops
30
+ from tensorflow.python.ops import state_ops
31
+ from tensorflow.python.ops import variable_scope
32
+ from tensorflow.python.platform import gfile
33
+ from tensorflow.python.platform import tf_logging
34
+ from tensorflow.python.summary import summary_iterator
35
+ from tensorflow.python.training import basic_session_run_hooks
36
+ from tensorflow.python.training import session_run_hook
37
+ from tensorflow.python.training import training_util
38
+
39
+ from easy_rec.python.utils.config_util import parse_time
40
+ from easy_rec.python.utils.load_class import load_by_path
41
+
42
+ if LooseVersion(tf.__version__) >= LooseVersion('2.12.0'):
43
+ from tensorflow_estimator.python.estimator.estimator_export import estimator_export
44
+ else:
45
+ from tensorflow.python.util.tf_export import estimator_export
46
+
47
+ _EVENT_FILE_GLOB_PATTERN = 'events.out.tfevents.*'
48
+
49
+ EARLY_STOP_SIG_SCOPE = 'signal_early_stopping'
50
+ EARLY_STOP_SIG_NAME = 'STOP'
51
+
52
+
53
+ def find_early_stop_var(var_list):
54
+ pattern = EARLY_STOP_SIG_SCOPE + '/' + EARLY_STOP_SIG_NAME
55
+ for var in var_list:
56
+ if pattern in var.name:
57
+ return var
58
+ return None
59
+
60
+
61
+ @estimator_export('estimator.experimental.make_early_stopping_hook')
62
+ def make_early_stopping_hook(estimator,
63
+ should_stop_fn,
64
+ run_every_secs=60,
65
+ run_every_steps=None):
66
+ """Creates early-stopping hook.
67
+
68
+ Returns a `SessionRunHook` that stops training when `should_stop_fn` returns `True`. Usage example:
69
+ ```python
70
+ estimator = ...
71
+ hook = early_stopping.make_early_stopping_hook(
72
+ estimator, should_stop_fn=make_stop_fn(...))
73
+ train_spec = tf.estimator.TrainSpec(..., hooks=[hook])
74
+ tf.estimator.train_and_evaluate(estimator, train_spec, ...)
75
+ ```
76
+
77
+ Caveat: Current implementation supports early-stopping both training and
78
+ evaluation in local mode. In distributed mode, training can be stopped but
79
+ evaluation (where it's a separate job) will indefinitely wait for new model
80
+ checkpoints to evaluate, so you will need other means to detect and stop it.
81
+ Early-stopping evaluation in distributed mode requires changes in
82
+ `train_and_evaluate` API and will be addressed in a future revision.
83
+
84
+ Args:
85
+ estimator: A `tf.estimator.Estimator` instance.
86
+ should_stop_fn: `callable`, function that takes no arguments and returns a
87
+ `bool`. If the function returns `True`, stopping will be initiated by the
88
+ chief.
89
+ run_every_secs: If specified, calls `should_stop_fn` at an interval of
90
+ `run_every_secs` seconds. Defaults to 60 seconds. Either this or
91
+ `run_every_steps` must be set.
92
+ run_every_steps: If specified, calls `should_stop_fn` every
93
+ `run_every_steps` steps. Either this or `run_every_secs` must be set.
94
+
95
+ Returns:
96
+ A `SessionRunHook` that periodically executes `should_stop_fn` and initiates
97
+ early stopping if the function returns `True`.
98
+
99
+ Raises:
100
+ TypeError: If `estimator` is not of type `tf.estimator.Estimator`.
101
+ ValueError: If both `run_every_secs` and `run_every_steps` are set.
102
+ """
103
+ if run_every_secs is not None and run_every_steps is not None:
104
+ raise ValueError('Only one of `run_every_secs` and `run_every_steps` must '
105
+ 'be set.')
106
+
107
+ if estimator.config.is_chief:
108
+ return _StopOnPredicateHook(should_stop_fn, run_every_secs, run_every_steps)
109
+ else:
110
+ return _CheckForStoppingHook()
111
+
112
+
113
+ @estimator_export('estimator.experimental.stop_if_higher_hook')
114
+ def stop_if_higher_hook(estimator,
115
+ metric_name,
116
+ threshold,
117
+ eval_dir=None,
118
+ min_steps=0,
119
+ run_every_secs=60,
120
+ run_every_steps=None):
121
+ """Creates hook to stop if the given metric is higher than the threshold.
122
+
123
+ Usage example:
124
+
125
+ ```python
126
+ estimator = ...
127
+ # Hook to stop training if accuracy becomes higher than 0.9.
128
+ hook = early_stopping.stop_if_higher_hook(estimator, "accuracy", 0.9)
129
+ train_spec = tf.estimator.TrainSpec(..., hooks=[hook])
130
+ tf.estimator.train_and_evaluate(estimator, train_spec, ...)
131
+ ```
132
+
133
+ Caveat: Current implementation supports early-stopping both training and
134
+ evaluation in local mode. In distributed mode, training can be stopped but
135
+ evaluation (where it's a separate job) will indefinitely wait for new model
136
+ checkpoints to evaluate, so you will need other means to detect and stop it.
137
+ Early-stopping evaluation in distributed mode requires changes in
138
+ `train_and_evaluate` API and will be addressed in a future revision.
139
+
140
+ Args:
141
+ estimator: A `tf.estimator.Estimator` instance.
142
+ metric_name: `str`, metric to track. "loss", "accuracy", etc.
143
+ threshold: Numeric threshold for the given metric.
144
+ eval_dir: If set, directory containing summary files with eval metrics. By
145
+ default, `estimator.eval_dir()` will be used.
146
+ min_steps: `int`, stop is never requested if global step is less than this
147
+ value. Defaults to 0.
148
+ run_every_secs: If specified, calls `should_stop_fn` at an interval of
149
+ `run_every_secs` seconds. Defaults to 60 seconds. Either this or
150
+ `run_every_steps` must be set.
151
+ run_every_steps: If specified, calls `should_stop_fn` every
152
+ `run_every_steps` steps. Either this or `run_every_secs` must be set.
153
+
154
+ Returns:
155
+ An early-stopping hook of type `SessionRunHook` that periodically checks
156
+ if the given metric is higher than specified threshold and initiates
157
+ early stopping if true.
158
+ """
159
+ return _stop_if_threshold_crossed_hook(
160
+ estimator=estimator,
161
+ metric_name=metric_name,
162
+ threshold=threshold,
163
+ higher_is_better=True,
164
+ eval_dir=eval_dir,
165
+ min_steps=min_steps,
166
+ run_every_secs=run_every_secs,
167
+ run_every_steps=run_every_steps)
168
+
169
+
170
+ @estimator_export('estimator.experimental.stop_if_lower_hook')
171
+ def stop_if_lower_hook(estimator,
172
+ metric_name,
173
+ threshold,
174
+ eval_dir=None,
175
+ min_steps=0,
176
+ run_every_secs=60,
177
+ run_every_steps=None):
178
+ """Creates hook to stop if the given metric is lower than the threshold.
179
+
180
+ Usage example:
181
+
182
+ ```python
183
+ estimator = ...
184
+ # Hook to stop training if loss becomes lower than 100.
185
+ hook = early_stopping.stop_if_lower_hook(estimator, "loss", 100)
186
+ train_spec = tf.estimator.TrainSpec(..., hooks=[hook])
187
+ tf.estimator.train_and_evaluate(estimator, train_spec, ...)
188
+ ```
189
+
190
+ Caveat: Current implementation supports early-stopping both training and
191
+ evaluation in local mode. In distributed mode, training can be stopped but
192
+ evaluation (where it's a separate job) will indefinitely wait for new model
193
+ checkpoints to evaluate, so you will need other means to detect and stop it.
194
+ Early-stopping evaluation in distributed mode requires changes in
195
+ `train_and_evaluate` API and will be addressed in a future revision.
196
+
197
+ Args:
198
+ estimator: A `tf.estimator.Estimator` instance.
199
+ metric_name: `str`, metric to track. "loss", "accuracy", etc.
200
+ threshold: Numeric threshold for the given metric.
201
+ eval_dir: If set, directory containing summary files with eval metrics. By
202
+ default, `estimator.eval_dir()` will be used.
203
+ min_steps: `int`, stop is never requested if global step is less than this
204
+ value. Defaults to 0.
205
+ run_every_secs: If specified, calls `should_stop_fn` at an interval of
206
+ `run_every_secs` seconds. Defaults to 60 seconds. Either this or
207
+ `run_every_steps` must be set.
208
+ run_every_steps: If specified, calls `should_stop_fn` every
209
+ `run_every_steps` steps. Either this or `run_every_secs` must be set.
210
+
211
+ Returns:
212
+ An early-stopping hook of type `SessionRunHook` that periodically checks
213
+ if the given metric is lower than specified threshold and initiates
214
+ early stopping if true.
215
+ """
216
+ return _stop_if_threshold_crossed_hook(
217
+ estimator=estimator,
218
+ metric_name=metric_name,
219
+ threshold=threshold,
220
+ higher_is_better=False,
221
+ eval_dir=eval_dir,
222
+ min_steps=min_steps,
223
+ run_every_secs=run_every_secs,
224
+ run_every_steps=run_every_steps)
225
+
226
+
227
+ @estimator_export('estimator.experimental.stop_if_no_increase_hook')
228
+ def stop_if_no_increase_hook(estimator,
229
+ metric_name,
230
+ max_steps_without_increase,
231
+ eval_dir=None,
232
+ min_steps=0,
233
+ run_every_secs=60,
234
+ run_every_steps=None):
235
+ """Creates hook to stop if metric does not increase within given max steps.
236
+
237
+ Usage example:
238
+
239
+ ```python
240
+ estimator = ...
241
+ # Hook to stop training if accuracy does not increase in over 100000 steps.
242
+ hook = early_stopping.stop_if_no_increase_hook(estimator, "accuracy", 100000)
243
+ train_spec = tf.estimator.TrainSpec(..., hooks=[hook])
244
+ tf.estimator.train_and_evaluate(estimator, train_spec, ...)
245
+ ```
246
+
247
+ Caveat: Current implementation supports early-stopping both training and
248
+ evaluation in local mode. In distributed mode, training can be stopped but
249
+ evaluation (where it's a separate job) will indefinitely wait for new model
250
+ checkpoints to evaluate, so you will need other means to detect and stop it.
251
+ Early-stopping evaluation in distributed mode requires changes in
252
+ `train_and_evaluate` API and will be addressed in a future revision.
253
+
254
+ Args:
255
+ estimator: A `tf.estimator.Estimator` instance.
256
+ metric_name: `str`, metric to track. "loss", "accuracy", etc.
257
+ max_steps_without_increase: `int`, maximum number of training steps with no
258
+ increase in the given metric.
259
+ eval_dir: If set, directory containing summary files with eval metrics. By
260
+ default, `estimator.eval_dir()` will be used.
261
+ min_steps: `int`, stop is never requested if global step is less than this
262
+ value. Defaults to 0.
263
+ run_every_secs: If specified, calls `should_stop_fn` at an interval of
264
+ `run_every_secs` seconds. Defaults to 60 seconds. Either this or
265
+ `run_every_steps` must be set.
266
+ run_every_steps: If specified, calls `should_stop_fn` every
267
+ `run_every_steps` steps. Either this or `run_every_secs` must be set.
268
+
269
+ Returns:
270
+ An early-stopping hook of type `SessionRunHook` that periodically checks
271
+ if the given metric shows no increase over given maximum number of
272
+ training steps, and initiates early stopping if true.
273
+ """
274
+ return _stop_if_no_metric_improvement_hook(
275
+ estimator=estimator,
276
+ metric_name=metric_name,
277
+ max_steps_without_improvement=max_steps_without_increase,
278
+ higher_is_better=True,
279
+ eval_dir=eval_dir,
280
+ min_steps=min_steps,
281
+ run_every_secs=run_every_secs,
282
+ run_every_steps=run_every_steps)
283
+
284
+
285
+ def custom_early_stop_hook(estimator,
286
+ eval_dir,
287
+ custom_stop_func,
288
+ custom_stop_func_params,
289
+ run_every_secs=60,
290
+ run_every_steps=None):
291
+ """Custom early stop hook for complex early stop conditions.
292
+
293
+ Args:
294
+ estimator: A `tf.estimator.Estimator` instance.
295
+ eval_dir: If set, directory containing summary files with eval metrics. By
296
+ default, `estimator.eval_dir()` will be used.
297
+ custom_stop_func: custom stop function, accept two parameters: eval_results,
298
+ custom_stop_func_params
299
+ custom_stop_func_params: string, parameters to custom_stop_func
300
+ run_every_secs: If specified, calls `should_stop_fn` at an interval of
301
+ `run_every_secs` seconds. Defaults to 60 seconds. Either this or
302
+ `run_every_steps` must be set.
303
+ run_every_steps: If specified, calls `should_stop_fn` every
304
+ `run_every_steps` steps. Either this or `run_every_secs` must be set.
305
+
306
+ Returns:
307
+ An early-stopping hook of type `SessionRunHook` that stop training and
308
+ evaluation under user defined conditions.
309
+ """
310
+ if eval_dir is None:
311
+ eval_dir = estimator.eval_dir()
312
+
313
+ if isinstance(custom_stop_func, str) or isinstance(custom_stop_func,
314
+ type(u'')):
315
+ custom_stop_func = load_by_path(custom_stop_func)
316
+
317
+ def _custom_stop_fn():
318
+ eval_results = read_eval_metrics(eval_dir)
319
+ return custom_stop_func(eval_results, custom_stop_func_params)
320
+
321
+ return make_early_stopping_hook(
322
+ estimator=estimator,
323
+ should_stop_fn=_custom_stop_fn,
324
+ run_every_secs=run_every_secs,
325
+ run_every_steps=run_every_steps)
326
+
327
+
328
+ @estimator_export('estimator.experimental.stop_if_no_decrease_hook')
329
+ def stop_if_no_decrease_hook(estimator,
330
+ metric_name,
331
+ max_steps_without_decrease,
332
+ eval_dir=None,
333
+ min_steps=0,
334
+ run_every_secs=60,
335
+ run_every_steps=None):
336
+ """Creates hook to stop if metric does not decrease within given max steps.
337
+
338
+ Usage example:
339
+
340
+ ```python
341
+ estimator = ...
342
+ # Hook to stop training if loss does not decrease in over 100000 steps.
343
+ hook = early_stopping.stop_if_no_decrease_hook(estimator, "loss", 100000)
344
+ train_spec = tf.estimator.TrainSpec(..., hooks=[hook])
345
+ tf.estimator.train_and_evaluate(estimator, train_spec, ...)
346
+ ```
347
+
348
+ Caveat: Current implementation supports early-stopping both training and
349
+ evaluation in local mode. In distributed mode, training can be stopped but
350
+ evaluation (where it's a separate job) will indefinitely wait for new model
351
+ checkpoints to evaluate, so you will need other means to detect and stop it.
352
+ Early-stopping evaluation in distributed mode requires changes in
353
+ `train_and_evaluate` API and will be addressed in a future revision.
354
+
355
+ Args:
356
+ estimator: A `tf.estimator.Estimator` instance.
357
+ metric_name: `str`, metric to track. "loss", "accuracy", etc.
358
+ max_steps_without_decrease: `int`, maximum number of training steps with no
359
+ decrease in the given metric.
360
+ eval_dir: If set, directory containing summary files with eval metrics. By
361
+ default, `estimator.eval_dir()` will be used.
362
+ min_steps: `int`, stop is never requested if global step is less than this
363
+ value. Defaults to 0.
364
+ run_every_secs: If specified, calls `should_stop_fn` at an interval of
365
+ `run_every_secs` seconds. Defaults to 60 seconds. Either this or
366
+ `run_every_steps` must be set.
367
+ run_every_steps: If specified, calls `should_stop_fn` every
368
+ `run_every_steps` steps. Either this or `run_every_secs` must be set.
369
+
370
+ Returns:
371
+ An early-stopping hook of type `SessionRunHook` that periodically checks
372
+ if the given metric shows no decrease over given maximum number of
373
+ training steps, and initiates early stopping if true.
374
+ """
375
+ return _stop_if_no_metric_improvement_hook(
376
+ estimator=estimator,
377
+ metric_name=metric_name,
378
+ max_steps_without_improvement=max_steps_without_decrease,
379
+ higher_is_better=False,
380
+ eval_dir=eval_dir,
381
+ min_steps=min_steps,
382
+ run_every_secs=run_every_secs,
383
+ run_every_steps=run_every_steps)
384
+
385
+
386
+ def read_eval_metrics(eval_dir):
387
+ """Helper to read eval metrics from eval summary files.
388
+
389
+ Args:
390
+ eval_dir: Directory containing summary files with eval metrics.
391
+
392
+ Returns:
393
+ A `dict` with global steps mapping to `dict` of metric names and values.
394
+ """
395
+ eval_metrics_dict = collections.defaultdict(dict)
396
+ for event in _summaries(eval_dir):
397
+ if not event.HasField('summary'):
398
+ continue
399
+ metrics = {}
400
+ for value in event.summary.value:
401
+ if value.HasField('simple_value'):
402
+ metrics[value.tag] = value.simple_value
403
+ if metrics:
404
+ eval_metrics_dict[event.step].update(metrics)
405
+ return collections.OrderedDict(
406
+ sorted(eval_metrics_dict.items(), key=lambda t: t[0]))
407
+
408
+
409
+ def _stop_if_threshold_crossed_hook(estimator, metric_name, threshold,
410
+ higher_is_better, eval_dir, min_steps,
411
+ run_every_secs, run_every_steps):
412
+ """Creates early-stopping hook to stop training if threshold is crossed."""
413
+ if eval_dir is None:
414
+ eval_dir = estimator.eval_dir()
415
+
416
+ is_lhs_better = operator.gt if higher_is_better else operator.lt
417
+ greater_or_lesser = 'greater than' if higher_is_better else 'less than'
418
+
419
+ def stop_if_threshold_crossed_fn():
420
+ """Returns `True` if the given metric crosses specified threshold."""
421
+ eval_results = read_eval_metrics(eval_dir)
422
+
423
+ for step, metrics in eval_results.items():
424
+ if step < min_steps:
425
+ continue
426
+ val = metrics[metric_name]
427
+ if is_lhs_better(val, threshold):
428
+ tf_logging.info(
429
+ 'At step %s, metric "%s" has value %s which is %s the configured '
430
+ 'threshold (%s) for early stopping.', step, metric_name, val,
431
+ greater_or_lesser, threshold)
432
+ return True
433
+ return False
434
+
435
+ return make_early_stopping_hook(
436
+ estimator=estimator,
437
+ should_stop_fn=stop_if_threshold_crossed_fn,
438
+ run_every_secs=run_every_secs,
439
+ run_every_steps=run_every_steps)
440
+
441
+
442
+ def _stop_if_no_metric_improvement_hook(estimator, metric_name,
443
+ max_steps_without_improvement,
444
+ higher_is_better, eval_dir, min_steps,
445
+ run_every_secs, run_every_steps):
446
+ """Returns hook to stop training if given metric shows no improvement."""
447
+ if eval_dir is None:
448
+ eval_dir = estimator.eval_dir()
449
+
450
+ is_lhs_better = operator.gt if higher_is_better else operator.lt
451
+ increase_or_decrease = 'increase' if higher_is_better else 'decrease'
452
+
453
+ def stop_if_no_metric_improvement_fn():
454
+ """Returns `True` if metric does not improve within max steps."""
455
+ eval_results = read_eval_metrics(eval_dir)
456
+
457
+ best_val = None
458
+ best_val_step = None
459
+ for step, metrics in eval_results.items():
460
+ if step < min_steps:
461
+ continue
462
+ val = metrics[metric_name]
463
+ if best_val is None or is_lhs_better(val, best_val):
464
+ best_val = val
465
+ best_val_step = step
466
+ if step - best_val_step >= max_steps_without_improvement:
467
+ tf_logging.info(
468
+ 'No %s in metric "%s" for %s steps, which is greater than or equal '
469
+ 'to max steps (%s) configured for early stopping.',
470
+ increase_or_decrease, metric_name, step - best_val_step,
471
+ max_steps_without_improvement)
472
+ return True
473
+ return False
474
+
475
+ return make_early_stopping_hook(
476
+ estimator=estimator,
477
+ should_stop_fn=stop_if_no_metric_improvement_fn,
478
+ run_every_secs=run_every_secs,
479
+ run_every_steps=run_every_steps)
480
+
481
+
482
+ def _summaries(eval_dir):
483
+ """Yields `tensorflow.Event` protos from event files in the eval dir.
484
+
485
+ Args:
486
+ eval_dir: Directory containing summary files with eval metrics.
487
+
488
+ Yields:
489
+ `tensorflow.Event` object read from the event files.
490
+ """
491
+ if gfile.Exists(eval_dir):
492
+ for event_file in gfile.Glob(
493
+ os.path.join(eval_dir, _EVENT_FILE_GLOB_PATTERN)):
494
+ for event in summary_iterator.summary_iterator(event_file):
495
+ yield event
496
+
497
+
498
+ def _get_or_create_stop_var():
499
+ with variable_scope.variable_scope(
500
+ name_or_scope=EARLY_STOP_SIG_SCOPE,
501
+ values=[],
502
+ reuse=variable_scope.AUTO_REUSE):
503
+ return variable_scope.get_variable(
504
+ name=EARLY_STOP_SIG_NAME,
505
+ shape=[],
506
+ dtype=dtypes.bool,
507
+ initializer=init_ops.constant_initializer(False),
508
+ collections=[ops.GraphKeys.GLOBAL_VARIABLES],
509
+ trainable=False)
510
+
511
+
512
+ class _StopOnPredicateHook(session_run_hook.SessionRunHook):
513
+ """Hook that requests stop when `should_stop_fn` returns `True`."""
514
+
515
+ def __init__(self, should_stop_fn, run_every_secs=60, run_every_steps=None):
516
+ if not callable(should_stop_fn):
517
+ raise TypeError('`should_stop_fn` must be callable.')
518
+
519
+ self._should_stop_fn = should_stop_fn
520
+ self._timer = basic_session_run_hooks.SecondOrStepTimer(
521
+ every_secs=run_every_secs, every_steps=run_every_steps)
522
+ self._global_step_tensor = None
523
+ self._stop_var = _get_or_create_stop_var()
524
+ self._stop_op = None
525
+
526
+ def begin(self):
527
+ self._global_step_tensor = training_util.get_global_step()
528
+ self._stop_op = state_ops.assign(self._stop_var, True)
529
+
530
+ def before_run(self, run_context):
531
+ del run_context
532
+ return session_run_hook.SessionRunArgs(self._global_step_tensor)
533
+
534
+ def after_run(self, run_context, run_values):
535
+ global_step = run_values.results
536
+ if self._timer.should_trigger_for_step(global_step):
537
+ self._timer.update_last_triggered_step(global_step)
538
+ if self._should_stop_fn():
539
+ tf_logging.info('Requesting early stopping at global step %d',
540
+ global_step)
541
+ run_context.session.run(self._stop_op)
542
+ run_context.request_stop()
543
+
544
+
545
+ class _CheckForStoppingHook(session_run_hook.SessionRunHook):
546
+ """Hook that requests stop if stop is requested by `_StopOnPredicateHook`."""
547
+
548
+ def __init__(self):
549
+ self._stop_var = None
550
+
551
+ def begin(self):
552
+ self._stop_var = _get_or_create_stop_var()
553
+
554
+ def before_run(self, run_context):
555
+ del run_context
556
+ return session_run_hook.SessionRunArgs(self._stop_var)
557
+
558
+ def after_run(self, run_context, run_values):
559
+ should_early_stop = run_values.results
560
+ if should_early_stop:
561
+ tf_logging.info('Early stopping requested, suspending run.')
562
+ run_context.request_stop()
563
+
564
+
565
+ class OssStopSignalHook(session_run_hook.SessionRunHook):
566
+
567
+ def __init__(self, model_dir, run_every_secs=10, run_every_steps=None):
568
+ self._stop_sig_file = os.path.join(model_dir, 'OSS_STOP_SIGNAL')
569
+ self._stop = False
570
+ self._check_run = True
571
+ self._timer = basic_session_run_hooks.SecondOrStepTimer(
572
+ every_secs=run_every_secs, every_steps=run_every_steps)
573
+ sleep_time = run_every_secs if run_every_secs is not None else 1
574
+ self._curr_step = 0
575
+
576
+ def _check_stop():
577
+ while self._check_run:
578
+ if self._timer.should_trigger_for_step(self._curr_step):
579
+ self._timer.update_last_triggered_step(self._curr_step)
580
+ if gfile.Exists(self._stop_sig_file):
581
+ self._stop = True
582
+ logging.info('OssStopSignalHook: stop on signal %s' %
583
+ self._stop_sig_file)
584
+ break
585
+ else:
586
+ time.sleep(sleep_time)
587
+
588
+ self._th = threading.Thread(target=_check_stop)
589
+ self._th.start()
590
+
591
+ self._global_step_tensor = None
592
+ self._stop_var = _get_or_create_stop_var()
593
+ self._stop_op = None
594
+
595
+ def begin(self):
596
+ self._global_step_tensor = training_util.get_global_step()
597
+ self._stop_op = state_ops.assign(self._stop_var, True)
598
+
599
+ def before_run(self, run_context):
600
+ return session_run_hook.SessionRunArgs(self._global_step_tensor)
601
+
602
+ def after_run(self, run_context, run_values):
603
+ if self._stop:
604
+ run_context.request_stop()
605
+ run_context.session.run(self._stop_op)
606
+ self._curr_step = run_values.results
607
+
608
+ def end(self, session):
609
+ self._check_run = False
610
+ self._th.join()
611
+
612
+
613
+ def oss_stop_hook(estimator, run_every_secs=10, run_every_steps=None):
614
+ """Creates oss stop hook.
615
+
616
+ Returns a `SessionRunHook` that stops training when model_dir/OSS_STOP_SIGNAL is created.
617
+ """
618
+ if estimator.config.is_chief:
619
+ return OssStopSignalHook(
620
+ estimator.model_dir,
621
+ run_every_secs=run_every_secs,
622
+ run_every_steps=run_every_steps)
623
+ else:
624
+ return _CheckForStoppingHook()
625
+
626
+
627
+ class DeadlineStopHook(session_run_hook.SessionRunHook):
628
+
629
+ def __init__(self, deadline_ts):
630
+ self._deadline_ts = deadline_ts
631
+ self._stop_var = _get_or_create_stop_var()
632
+ self._stop_op = None
633
+
634
+ def begin(self):
635
+ self._stop_op = state_ops.assign(self._stop_var, True)
636
+
637
+ def after_run(self, run_context, run_values):
638
+ curr_ts = time.mktime(datetime.datetime.now().timetuple())
639
+ if curr_ts > self._deadline_ts:
640
+ run_context.request_stop()
641
+ run_context.session.run(self._stop_op)
642
+
643
+
644
+ def deadline_stop_hook(estimator, dead_line):
645
+ """Creates oss stop hook.
646
+
647
+ Returns a `SessionRunHook` that stops training when timestamp > deadline_ts.
648
+ """
649
+ deadline_ts = parse_time(dead_line)
650
+ if estimator.config.is_chief:
651
+ return DeadlineStopHook(deadline_ts)
652
+ else:
653
+ return _CheckForStoppingHook()