restore_test.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. # MIT License
  2. #
  3. # Copyright (c) 2016 David Sandberg
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in all
  13. # copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. import unittest
  23. import tempfile
  24. import os
  25. import shutil
  26. import tensorflow as tf
  27. import numpy as np
  28. class TrainTest(unittest.TestCase):
  29. @classmethod
  30. def setUpClass(self):
  31. self.tmp_dir = tempfile.mkdtemp()
  32. @classmethod
  33. def tearDownClass(self):
  34. # Recursively remove the temporary directory
  35. shutil.rmtree(self.tmp_dir)
  36. def test_restore_noema(self):
  37. # Create 100 phony x, y data points in NumPy, y = x * 0.1 + 0.3
  38. x_data = np.random.rand(100).astype(np.float32)
  39. y_data = x_data * 0.1 + 0.3
  40. # Try to find values for W and b that compute y_data = W * x_data + b
  41. # (We know that W should be 0.1 and b 0.3, but TensorFlow will
  42. # figure that out for us.)
  43. W = tf.Variable(tf.random_uniform([1], -1.0, 1.0), name='W')
  44. b = tf.Variable(tf.zeros([1]), name='b')
  45. y = W * x_data + b
  46. # Minimize the mean squared errors.
  47. loss = tf.reduce_mean(tf.square(y - y_data))
  48. optimizer = tf.train.GradientDescentOptimizer(0.5)
  49. train = optimizer.minimize(loss)
  50. # Before starting, initialize the variables. We will 'run' this first.
  51. init = tf.global_variables_initializer()
  52. saver = tf.train.Saver(tf.trainable_variables())
  53. # Launch the graph.
  54. sess = tf.Session()
  55. sess.run(init)
  56. # Fit the line.
  57. for _ in range(201):
  58. sess.run(train)
  59. w_reference = sess.run('W:0')
  60. b_reference = sess.run('b:0')
  61. saver.save(sess, os.path.join(self.tmp_dir, "model_ex1"))
  62. tf.reset_default_graph()
  63. saver = tf.train.import_meta_graph(os.path.join(self.tmp_dir, "model_ex1.meta"))
  64. sess = tf.Session()
  65. saver.restore(sess, os.path.join(self.tmp_dir, "model_ex1"))
  66. w_restored = sess.run('W:0')
  67. b_restored = sess.run('b:0')
  68. self.assertAlmostEqual(w_reference, w_restored, 'Restored model use different weight than the original model')
  69. self.assertAlmostEqual(b_reference, b_restored, 'Restored model use different weight than the original model')
  70. @unittest.skip("Skip restore EMA test case for now")
  71. def test_restore_ema(self):
  72. # Create 100 phony x, y data points in NumPy, y = x * 0.1 + 0.3
  73. x_data = np.random.rand(100).astype(np.float32)
  74. y_data = x_data * 0.1 + 0.3
  75. # Try to find values for W and b that compute y_data = W * x_data + b
  76. # (We know that W should be 0.1 and b 0.3, but TensorFlow will
  77. # figure that out for us.)
  78. W = tf.Variable(tf.random_uniform([1], -1.0, 1.0), name='W')
  79. b = tf.Variable(tf.zeros([1]), name='b')
  80. y = W * x_data + b
  81. # Minimize the mean squared errors.
  82. loss = tf.reduce_mean(tf.square(y - y_data))
  83. optimizer = tf.train.GradientDescentOptimizer(0.5)
  84. opt_op = optimizer.minimize(loss)
  85. # Track the moving averages of all trainable variables.
  86. ema = tf.train.ExponentialMovingAverage(decay=0.9999)
  87. averages_op = ema.apply(tf.trainable_variables())
  88. with tf.control_dependencies([opt_op]):
  89. train_op = tf.group(averages_op)
  90. # Before starting, initialize the variables. We will 'run' this first.
  91. init = tf.global_variables_initializer()
  92. saver = tf.train.Saver(tf.trainable_variables())
  93. # Launch the graph.
  94. sess = tf.Session()
  95. sess.run(init)
  96. # Fit the line.
  97. for _ in range(201):
  98. sess.run(train_op)
  99. w_reference = sess.run('W/ExponentialMovingAverage:0')
  100. b_reference = sess.run('b/ExponentialMovingAverage:0')
  101. saver.save(sess, os.path.join(self.tmp_dir, "model_ex1"))
  102. tf.reset_default_graph()
  103. tf.train.import_meta_graph(os.path.join(self.tmp_dir, "model_ex1.meta"))
  104. sess = tf.Session()
  105. print('------------------------------------------------------')
  106. for var in tf.global_variables():
  107. print('all variables: ' + var.op.name)
  108. for var in tf.trainable_variables():
  109. print('normal variable: ' + var.op.name)
  110. for var in tf.moving_average_variables():
  111. print('ema variable: ' + var.op.name)
  112. print('------------------------------------------------------')
  113. mode = 1
  114. restore_vars = {}
  115. if mode == 0:
  116. ema = tf.train.ExponentialMovingAverage(1.0)
  117. for var in tf.trainable_variables():
  118. print('%s: %s' % (ema.average_name(var), var.op.name))
  119. restore_vars[ema.average_name(var)] = var
  120. elif mode == 1:
  121. for var in tf.trainable_variables():
  122. ema_name = var.op.name + '/ExponentialMovingAverage'
  123. print('%s: %s' % (ema_name, var.op.name))
  124. restore_vars[ema_name] = var
  125. saver = tf.train.Saver(restore_vars, name='ema_restore')
  126. saver.restore(sess, os.path.join(self.tmp_dir, "model_ex1"))
  127. w_restored = sess.run('W:0')
  128. b_restored = sess.run('b:0')
  129. self.assertAlmostEqual(w_reference, w_restored, 'Restored model modes not use the EMA filtered weight')
  130. self.assertAlmostEqual(b_reference, b_restored, 'Restored model modes not use the EMA filtered bias')
  131. # Create a checkpoint file pointing to the model
  132. def create_checkpoint_file(model_dir, model_file):
  133. checkpoint_filename = os.path.join(model_dir, 'checkpoint')
  134. full_model_filename = os.path.join(model_dir, model_file)
  135. with open(checkpoint_filename, 'w') as f:
  136. f.write('model_checkpoint_path: "%s"\n' % full_model_filename)
  137. f.write('all_model_checkpoint_paths: "%s"\n' % full_model_filename)
  138. if __name__ == "__main__":
  139. unittest.main()