aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/python/training/supervisor_test.py
blob: dda0166aa630f5fb2841629c9971f0350dbee352 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for supervisor.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import glob
import os
import shutil
import time
import uuid

from six.moves import xrange  # pylint: disable=redefined-builtin
import tensorflow as tf

from tensorflow.core.protobuf import meta_graph_pb2
from tensorflow.python.framework import meta_graph


def _summary_iterator(test_dir):
  """Reads events from test_dir/events.

  Args:
    test_dir: Name of the test directory.

  Returns:
    A summary_iterator
  """
  event_paths = sorted(glob.glob(os.path.join(test_dir, "event*")))
  return tf.train.summary_iterator(event_paths[-1])


def _test_dir(test_name):
  test_dir = os.path.join(tf.test.get_temp_dir(), test_name)
  if os.path.exists(test_dir):
    shutil.rmtree(test_dir)
  return test_dir


class SupervisorTest(tf.test.TestCase):

  def _wait_for_glob(self, pattern, timeout_secs, for_checkpoint=True):
    """Wait for a checkpoint file to appear.

    Args:
      pattern: A string.
      timeout_secs: How long to wait for in seconds.
      for_checkpoint: whether we're globbing for checkpoints.
    """
    end_time = time.time() + timeout_secs
    while time.time() < end_time:
      if for_checkpoint:
        if tf.train.checkpoint_exists(pattern):
          return
      else:
        if len(tf.gfile.Glob(pattern)) >= 1:
          return
      time.sleep(0.05)
    self.assertFalse(True, "Glob never matched any file: %s" % pattern)

  # This test does not test much.
  def testBasics(self):
    logdir = _test_dir("basics")
    with tf.Graph().as_default():
      my_op = tf.constant(1.0)
      sv = tf.train.Supervisor(logdir=logdir)
      sess = sv.prepare_or_wait_for_session("")
      for _ in xrange(10):
        sess.run(my_op)
      sess.close()
      sv.stop()

  def testManagedSession(self):
    logdir = _test_dir("managed_session")
    with tf.Graph().as_default():
      my_op = tf.constant(1.0)
      sv = tf.train.Supervisor(logdir=logdir)
      with sv.managed_session("") as sess:
        for _ in xrange(10):
          sess.run(my_op)
      # Supervisor has been stopped.
      self.assertTrue(sv.should_stop())

  def testManagedSessionUserError(self):
    logdir = _test_dir("managed_user_error")
    with tf.Graph().as_default():
      my_op = tf.constant(1.0)
      sv = tf.train.Supervisor(logdir=logdir)
      last_step = None
      with self.assertRaisesRegexp(RuntimeError, "failing here"):
        with sv.managed_session("") as sess:
          for step in xrange(10):
            last_step = step
            if step == 1:
              raise RuntimeError("failing here")
            else:
              sess.run(my_op)
      # Supervisor has been stopped.
      self.assertTrue(sv.should_stop())
      self.assertEqual(1, last_step)

  def testManagedSessionIgnoreOutOfRangeError(self):
    logdir = _test_dir("managed_out_of_range")
    with tf.Graph().as_default():
      my_op = tf.constant(1.0)
      sv = tf.train.Supervisor(logdir=logdir)
      last_step = None
      with sv.managed_session("") as sess:
        for step in xrange(10):
          last_step = step
          if step == 3:
            raise tf.errors.OutOfRangeError(my_op.op.node_def, my_op.op,
                                            "all done")
          else:
            sess.run(my_op)
      # Supervisor has been stopped.  OutOfRangeError was not thrown.
      self.assertTrue(sv.should_stop())
      self.assertEqual(3, last_step)

  def testManagedSessionDoNotKeepSummaryWriter(self):
    logdir = _test_dir("managed_not_keep_summary_writer")
    with tf.Graph().as_default():
      tf.summary.scalar("c1", tf.constant(1))
      tf.summary.scalar("c2", tf.constant(2))
      tf.summary.scalar("c3", tf.constant(3))
      summ = tf.summary.merge_all()
      sv = tf.train.Supervisor(logdir=logdir, summary_op=None)
      with sv.managed_session("", close_summary_writer=True,
                              start_standard_services=False) as sess:
        sv.summary_computed(sess, sess.run(summ))
      # Sleep 1.2s to make sure that the next event file has a different name
      # than the current one.
      time.sleep(1.2)
      with sv.managed_session("", close_summary_writer=True,
                              start_standard_services=False) as sess:
        sv.summary_computed(sess, sess.run(summ))
    event_paths = sorted(glob.glob(os.path.join(logdir, "event*")))
    self.assertEquals(2, len(event_paths))
    # The two event files should have the same contents.
    for path in event_paths:
      # The summary iterator should report the summary once as we closed the
      # summary writer across the 2 sessions.
      rr = tf.train.summary_iterator(path)
      # The first event should list the file_version.
      ev = next(rr)
      self.assertEquals("brain.Event:2", ev.file_version)

      # The next one has the graph and metagraph.
      ev = next(rr)
      self.assertTrue(ev.graph_def)

      ev = next(rr)
      self.assertTrue(ev.meta_graph_def)

      # The next one should have the values from the summary.
      # But only once.
      ev = next(rr)
      self.assertProtoEquals("""
        value { tag: 'c1' simple_value: 1.0 }
        value { tag: 'c2' simple_value: 2.0 }
        value { tag: 'c3' simple_value: 3.0 }
        """, ev.summary)

      # The next one should be a stop message if we closed cleanly.
      ev = next(rr)
      self.assertEquals(tf.SessionLog.STOP, ev.session_log.status)

      # We should be done.
      with self.assertRaises(StopIteration):
        next(rr)

  def testManagedSessionKeepSummaryWriter(self):
    logdir = _test_dir("managed_keep_summary_writer")
    with tf.Graph().as_default():
      tf.summary.scalar("c1", tf.constant(1))
      tf.summary.scalar("c2", tf.constant(2))
      tf.summary.scalar("c3", tf.constant(3))
      summ = tf.summary.merge_all()
      sv = tf.train.Supervisor(logdir=logdir)
      with sv.managed_session("", close_summary_writer=False,
                              start_standard_services=False) as sess:
        sv.summary_computed(sess, sess.run(summ))
      with sv.managed_session("", close_summary_writer=False,
                              start_standard_services=False) as sess:
        sv.summary_computed(sess, sess.run(summ))
    # Now close the summary writer to flush the events.
    sv.summary_writer.close()
    # The summary iterator should report the summary twice as we reused
    # the same summary writer across the 2 sessions.
    rr = _summary_iterator(logdir)
    # The first event should list the file_version.
    ev = next(rr)
    self.assertEquals("brain.Event:2", ev.file_version)

    # The next one has the graph.
    ev = next(rr)
    self.assertTrue(ev.graph_def)

    ev = next(rr)
    self.assertTrue(ev.meta_graph_def)

    # The next one should have the values from the summary.
    ev = next(rr)
    self.assertProtoEquals("""
      value { tag: 'c1' simple_value: 1.0 }
      value { tag: 'c2' simple_value: 2.0 }
      value { tag: 'c3' simple_value: 3.0 }
      """, ev.summary)

    # The next one should also have the values from the summary.
    ev = next(rr)
    self.assertProtoEquals("""
      value { tag: 'c1' simple_value: 1.0 }
      value { tag: 'c2' simple_value: 2.0 }
      value { tag: 'c3' simple_value: 3.0 }
      """, ev.summary)

    # We should be done.
    self.assertRaises(StopIteration, lambda: next(rr))

  def _csv_data(self, logdir):
    # Create a small data file with 3 CSV records.
    data_path = os.path.join(logdir, "data.csv")
    with open(data_path, "w") as f:
      f.write("1,2,3\n")
      f.write("4,5,6\n")
      f.write("7,8,9\n")
    return data_path

  def testManagedEndOfInputOneQueue(self):
    # Tests that the supervisor finishes without an error when using
    # a fixed number of epochs, reading from a single queue.
    logdir = _test_dir("managed_end_of_input_one_queue")
    os.makedirs(logdir)
    data_path = self._csv_data(logdir)
    with tf.Graph().as_default():
      # Create an input pipeline that reads the file 3 times.
      filename_queue = tf.train.string_input_producer([data_path], num_epochs=3)
      reader = tf.TextLineReader()
      _, csv = reader.read(filename_queue)
      rec = tf.decode_csv(csv, record_defaults=[[1], [1], [1]])
      sv = tf.train.Supervisor(logdir=logdir)
      with sv.managed_session("") as sess:
        while not sv.should_stop():
          sess.run(rec)

  def testManagedEndOfInputTwoQueues(self):
    # Tests that the supervisor finishes without an error when using
    # a fixed number of epochs, reading from two queues, the second
    # one producing a batch from the first one.
    logdir = _test_dir("managed_end_of_input_two_queues")
    os.makedirs(logdir)
    data_path = self._csv_data(logdir)
    with tf.Graph().as_default():
      # Create an input pipeline that reads the file 3 times.
      filename_queue = tf.train.string_input_producer([data_path], num_epochs=3)
      reader = tf.TextLineReader()
      _, csv = reader.read(filename_queue)
      rec = tf.decode_csv(csv, record_defaults=[[1], [1], [1]])
      shuff_rec = tf.train.shuffle_batch(rec, 1, 6, 4)
      sv = tf.train.Supervisor(logdir=logdir)
      with sv.managed_session("") as sess:
        while not sv.should_stop():
          sess.run(shuff_rec)

  def testManagedMainErrorTwoQueues(self):
    # Tests that the supervisor correctly raises a main loop
    # error even when using multiple queues for input.
    logdir = _test_dir("managed_main_error_two_queues")
    os.makedirs(logdir)
    data_path = self._csv_data(logdir)
    with self.assertRaisesRegexp(RuntimeError, "fail at step 3"):
      with tf.Graph().as_default():
        # Create an input pipeline that reads the file 3 times.
        filename_queue = tf.train.string_input_producer([data_path],
                                                        num_epochs=3)
        reader = tf.TextLineReader()
        _, csv = reader.read(filename_queue)
        rec = tf.decode_csv(csv, record_defaults=[[1], [1], [1]])
        shuff_rec = tf.train.shuffle_batch(rec, 1, 6, 4)
        sv = tf.train.Supervisor(logdir=logdir)
        with sv.managed_session("") as sess:
          for step in range(9):
            if sv.should_stop():
              break
            elif step == 3:
              raise RuntimeError("fail at step 3")
            else:
              sess.run(shuff_rec)

  def testSessionConfig(self):
    logdir = _test_dir("session_config")
    with tf.Graph().as_default():
      with tf.device("/cpu:1"):
        my_op = tf.constant([1.0])
      sv = tf.train.Supervisor(logdir=logdir)
      sess = sv.prepare_or_wait_for_session(
          "", config=tf.ConfigProto(device_count={"CPU": 2}))
      for _ in xrange(10):
        sess.run(my_op)
      sess.close()
      sv.stop()

  def testChiefCanWriteEvents(self):
    logdir = _test_dir("can_write")
    with tf.Graph().as_default():
      tf.summary.scalar("c1", tf.constant(1))
      tf.summary.scalar("c2", tf.constant(2))
      tf.summary.scalar("c3", tf.constant(3))
      summ = tf.summary.merge_all()
      sv = tf.train.Supervisor(is_chief=True, logdir=logdir, summary_op=None)
      meta_graph_def = meta_graph.create_meta_graph_def()
      sess = sv.prepare_or_wait_for_session("")
      sv.summary_computed(sess, sess.run(summ))
      sess.close()
      # Wait to make sure everything is written to file before stopping.
      time.sleep(1)
      sv.stop()

    rr = _summary_iterator(logdir)

    # The first event should list the file_version.
    ev = next(rr)
    self.assertEquals("brain.Event:2", ev.file_version)

    # The next one has the graph.
    ev = next(rr)
    ev_graph = tf.GraphDef()
    ev_graph.ParseFromString(ev.graph_def)
    self.assertProtoEquals(sess.graph.as_graph_def(add_shapes=True), ev_graph)

    # Stored MetaGraphDef
    ev = next(rr)
    ev_meta_graph = meta_graph_pb2.MetaGraphDef()
    ev_meta_graph.ParseFromString(ev.meta_graph_def)
    self.assertProtoEquals(meta_graph_def, ev_meta_graph)
    self.assertProtoEquals(
        sess.graph.as_graph_def(add_shapes=True), ev_meta_graph.graph_def)
    # The next one should have the values from the summary.
    ev = next(rr)
    self.assertProtoEquals("""
      value { tag: 'c1' simple_value: 1.0 }
      value { tag: 'c2' simple_value: 2.0 }
      value { tag: 'c3' simple_value: 3.0 }
      """, ev.summary)

    # The next one should be a stop message if we closed cleanly.
    ev = next(rr)
    self.assertEquals(tf.SessionLog.STOP, ev.session_log.status)

    # We should be done.
    self.assertRaises(StopIteration, lambda: next(rr))

  def testNonChiefCannotWriteEvents(self):

    def _summary_computed():
      with tf.Graph().as_default():
        sv = tf.train.Supervisor(is_chief=False)
        sess = sv.prepare_or_wait_for_session("")
        tf.summary.scalar("c1", tf.constant(1))
        tf.summary.scalar("c2", tf.constant(2))
        summ = tf.summary.merge_all()
        sv.summary_computed(sess, sess.run(summ))

    def _start_standard_services():
      with tf.Graph().as_default():
        sv = tf.train.Supervisor(is_chief=False)
        sess = sv.prepare_or_wait_for_session("")
        sv.start_standard_services(sess)

    self.assertRaises(RuntimeError, _summary_computed)
    self.assertRaises(RuntimeError, _start_standard_services)

  def testNoLogdirButWantSummary(self):
    with tf.Graph().as_default():
      tf.summary.scalar("c1", tf.constant(1))
      tf.summary.scalar("c2", tf.constant(2))
      tf.summary.scalar("c3", tf.constant(3))
      summ = tf.summary.merge_all()
      sv = tf.train.Supervisor(logdir="", summary_op=None)
      sess = sv.prepare_or_wait_for_session("")
      with self.assertRaisesRegexp(RuntimeError, "requires a summary writer"):
        sv.summary_computed(sess, sess.run(summ))

  def testLogdirButExplicitlyNoSummaryWriter(self):
    logdir = _test_dir("explicit_no_summary_writer")
    with tf.Graph().as_default():
      tf.Variable([1.0], name="foo")
      tf.summary.scalar("c1", tf.constant(1))
      tf.summary.scalar("c2", tf.constant(2))
      tf.summary.scalar("c3", tf.constant(3))
      summ = tf.summary.merge_all()
      sv = tf.train.Supervisor(logdir=logdir, summary_writer=None)
      sess = sv.prepare_or_wait_for_session("")
      # Check that a checkpoint is still be generated.
      self._wait_for_glob(sv.save_path, 3.0)
      # Check that we cannot write a summary
      with self.assertRaisesRegexp(RuntimeError, "requires a summary writer"):
        sv.summary_computed(sess, sess.run(summ))

  def testNoLogdirButExplicitSummaryWriter(self):
    logdir = _test_dir("explicit_summary_writer")
    with tf.Graph().as_default():
      tf.summary.scalar("c1", tf.constant(1))
      tf.summary.scalar("c2", tf.constant(2))
      tf.summary.scalar("c3", tf.constant(3))
      summ = tf.summary.merge_all()
      sw = tf.summary.FileWriter(logdir)
      sv = tf.train.Supervisor(logdir="", summary_op=None, summary_writer=sw)
      meta_graph_def = meta_graph.create_meta_graph_def()
      sess = sv.prepare_or_wait_for_session("")
      sv.summary_computed(sess, sess.run(summ))
      sess.close()
      # Wait to make sure everything is written to file before stopping.
      time.sleep(1)
      sv.stop()

    # Check the summary was written to 'logdir'
    rr = _summary_iterator(logdir)

    # The first event should list the file_version.
    ev = next(rr)
    self.assertEquals("brain.Event:2", ev.file_version)

    # The next one has the graph.
    ev = next(rr)
    ev_graph = tf.GraphDef()
    ev_graph.ParseFromString(ev.graph_def)
    self.assertProtoEquals(sess.graph.as_graph_def(add_shapes=True), ev_graph)

    # Stored MetaGraphDef
    ev = next(rr)
    ev_meta_graph = meta_graph_pb2.MetaGraphDef()
    ev_meta_graph.ParseFromString(ev.meta_graph_def)
    self.assertProtoEquals(meta_graph_def, ev_meta_graph)
    self.assertProtoEquals(
        sess.graph.as_graph_def(add_shapes=True), ev_meta_graph.graph_def)

    # The next one should have the values from the summary.
    ev = next(rr)
    self.assertProtoEquals("""
      value { tag: 'c1' simple_value: 1.0 }
      value { tag: 'c2' simple_value: 2.0 }
      value { tag: 'c3' simple_value: 3.0 }
      """, ev.summary)

    # The next one should be a stop message if we closed cleanly.
    ev = next(rr)
    self.assertEquals(tf.SessionLog.STOP, ev.session_log.status)

    # We should be done.
    self.assertRaises(StopIteration, lambda: next(rr))

  def testNoLogdirSucceeds(self):
    with tf.Graph().as_default():
      tf.Variable([1.0, 2.0, 3.0])
      sv = tf.train.Supervisor(logdir="", summary_op=None)
      sess = sv.prepare_or_wait_for_session("")
      sess.close()
      sv.stop()

  def testUseSessionManager(self):
    with tf.Graph().as_default():
      tf.Variable([1.0, 2.0, 3.0])
      sm = tf.train.SessionManager()
      # Pass in session_manager. The additional init_op is ignored.
      sv = tf.train.Supervisor(logdir="", session_manager=sm)
      sv.prepare_or_wait_for_session("")

  def testInitOp(self):
    logdir = _test_dir("default_init_op")
    with tf.Graph().as_default():
      v = tf.Variable([1.0, 2.0, 3.0])
      sv = tf.train.Supervisor(logdir=logdir)
      sess = sv.prepare_or_wait_for_session("")
      self.assertAllClose([1.0, 2.0, 3.0], sess.run(v))
      sv.stop()

  def testInitFn(self):
    logdir = _test_dir("default_init_op")
    with tf.Graph().as_default():
      v = tf.Variable([1.0, 2.0, 3.0])
      def _init_fn(sess):
        sess.run(v.initializer)
      sv = tf.train.Supervisor(logdir=logdir, init_op=None, init_fn=_init_fn)
      sess = sv.prepare_or_wait_for_session("")
      self.assertAllClose([1.0, 2.0, 3.0], sess.run(v))
      sv.stop()

  def testInitOpWithFeedDict(self):
    logdir = _test_dir("feed_dict_init_op")
    with tf.Graph().as_default():
      p = tf.placeholder(tf.float32, shape=(3,))
      v = tf.Variable(p, name="v")
      sv = tf.train.Supervisor(logdir=logdir,
                               init_op=tf.global_variables_initializer(),
                               init_feed_dict={p: [1.0, 2.0, 3.0]})
      sess = sv.prepare_or_wait_for_session("")
      self.assertAllClose([1.0, 2.0, 3.0], sess.run(v))
      sv.stop()

  def testReadyForLocalInitOp(self):
    server = tf.train.Server.create_local_server()
    logdir = _test_dir("default_ready_for_local_init_op")

    uid = uuid.uuid4().hex

    def get_session(is_chief):
      g = tf.Graph()
      with g.as_default():
        with tf.device("/job:local"):
          v = tf.Variable(
              1, name="default_ready_for_local_init_op_v_" + str(uid))
          vadd = v.assign_add(1)
          w = tf.Variable(
              v,
              trainable=False,
              collections=[tf.GraphKeys.LOCAL_VARIABLES],
              name="default_ready_for_local_init_op_w_" + str(uid))
          ready_for_local_init_op = tf.report_uninitialized_variables(
              tf.all_variables())
      sv = tf.train.Supervisor(
          logdir=logdir,
          is_chief=is_chief,
          graph=g,
          recovery_wait_secs=1,
          init_op=v.initializer,
          ready_for_local_init_op=ready_for_local_init_op)
      sess = sv.prepare_or_wait_for_session(server.target)

      return sv, sess, v, vadd, w

    sv0, sess0, v0, _, w0 = get_session(True)
    sv1, sess1, _, vadd1, w1 = get_session(False)

    self.assertEqual(1, sess0.run(w0))
    self.assertEqual(2, sess1.run(vadd1))
    self.assertEqual(1, sess1.run(w1))
    self.assertEqual(2, sess0.run(v0))

    sv0.stop()
    sv1.stop()

  def testReadyForLocalInitOpRestoreFromCheckpoint(self):
    server = tf.train.Server.create_local_server()
    logdir = _test_dir("ready_for_local_init_op_restore")

    uid = uuid.uuid4().hex

    # Create a checkpoint.
    with tf.Graph().as_default():
      v = tf.Variable(
          10.0, name="ready_for_local_init_op_restore_v_" + str(uid))
      tf.summary.scalar("ready_for_local_init_op_restore_v_" + str(uid), v)
      sv = tf.train.Supervisor(logdir=logdir)
      sv.prepare_or_wait_for_session(server.target)
      save_path = sv.save_path
      self._wait_for_glob(save_path, 3.0)
      self._wait_for_glob(
          os.path.join(logdir, "*events*"), 3.0, for_checkpoint=False)
      # Wait to make sure everything is written to file before stopping.
      time.sleep(1)
      sv.stop()

    def get_session(is_chief):
      g = tf.Graph()
      with g.as_default():
        with tf.device("/job:local"):
          v = tf.Variable(
              1.0, name="ready_for_local_init_op_restore_v_" + str(uid))
          vadd = v.assign_add(1)
          w = tf.Variable(
              v,
              trainable=False,
              collections=[tf.GraphKeys.LOCAL_VARIABLES],
              name="ready_for_local_init_op_restore_w_" + str(uid))
          ready_for_local_init_op = tf.report_uninitialized_variables(
              tf.all_variables())
      sv = tf.train.Supervisor(
          logdir=logdir,
          is_chief=is_chief,
          graph=g,
          recovery_wait_secs=1,
          ready_for_local_init_op=ready_for_local_init_op)
      sess = sv.prepare_or_wait_for_session(server.target)

      return sv, sess, v, vadd, w

    sv0, sess0, v0, _, w0 = get_session(True)
    sv1, sess1, _, vadd1, w1 = get_session(False)

    self.assertEqual(10, sess0.run(w0))
    self.assertEqual(11, sess1.run(vadd1))
    self.assertEqual(10, sess1.run(w1))
    self.assertEqual(11, sess0.run(v0))

    sv0.stop()
    sv1.stop()

  def testLocalInitOp(self):
    logdir = _test_dir("default_local_init_op")
    with tf.Graph().as_default():
      # A local variable.
      v = tf.Variable([1.0, 2.0, 3.0],
                      trainable=False,
                      collections=[tf.GraphKeys.LOCAL_VARIABLES])

      # An entity which is initialized through a TABLE_INITIALIZER.
      w = tf.Variable([4, 5, 6], trainable=False, collections=[])
      tf.add_to_collection(tf.GraphKeys.TABLE_INITIALIZERS, w.initializer)

      # This shouldn't add a variable to the VARIABLES collection responsible
      # for variables that are saved/restored from checkpoints.
      self.assertEquals(len(tf.all_variables()), 0)

      # Suppress normal variable inits to make sure the local one is
      # initialized via local_init_op.
      sv = tf.train.Supervisor(logdir=logdir, init_op=None)
      sess = sv.prepare_or_wait_for_session("")
      self.assertAllClose([1.0, 2.0, 3.0], sess.run(v))
      self.assertAllClose([4, 5, 6], sess.run(w))
      sv.stop()

  def testLocalInitOpForNonChief(self):
    logdir = _test_dir("default_local_init_op_non_chief")
    with tf.Graph().as_default():
      with tf.device("/job:localhost"):
        # A local variable.
        v = tf.Variable([1.0, 2.0, 3.0],
                        trainable=False,
                        collections=[tf.GraphKeys.LOCAL_VARIABLES])
        # This shouldn't add a variable to the VARIABLES collection responsible
        # for variables that are saved/restored from checkpoints.
        self.assertEquals(len(tf.all_variables()), 0)

      # Suppress normal variable inits to make sure the local one is
      # initialized via local_init_op.
      sv = tf.train.Supervisor(logdir=logdir, init_op=None, is_chief=False)
      sess = sv.prepare_or_wait_for_session("")
      self.assertAllClose([1.0, 2.0, 3.0], sess.run(v))
      sv.stop()

  def testInitOpFails(self):
    server = tf.train.Server.create_local_server()
    logdir = _test_dir("default_init_op_fails")
    with tf.Graph().as_default():
      v = tf.Variable([1.0, 2.0, 3.0], name="v")
      tf.Variable([4.0, 5.0, 6.0], name="w")
      # w will not be initialized.
      sv = tf.train.Supervisor(logdir=logdir, init_op=v.initializer)
      with self.assertRaisesRegexp(RuntimeError,
                                   "Variables not initialized: w"):
        sv.prepare_or_wait_for_session(server.target)

  def testInitOpFailsForTransientVariable(self):
    server = tf.train.Server.create_local_server()
    logdir = _test_dir("default_init_op_fails_for_local_variable")
    with tf.Graph().as_default():
      v = tf.Variable([1.0, 2.0, 3.0], name="v",
                      collections=[tf.GraphKeys.LOCAL_VARIABLES])
      tf.Variable([1.0, 2.0, 3.0], name="w",
                  collections=[tf.GraphKeys.LOCAL_VARIABLES])
      # w will not be initialized.
      sv = tf.train.Supervisor(logdir=logdir, local_init_op=v.initializer)
      with self.assertRaisesRegexp(
          RuntimeError, "Variables not initialized: w"):
        sv.prepare_or_wait_for_session(server.target)

  def testSetupFail(self):
    logdir = _test_dir("setup_fail")
    with tf.Graph().as_default():
      tf.Variable([1.0, 2.0, 3.0], name="v")
      with self.assertRaisesRegexp(ValueError, "must have their device set"):
        tf.train.Supervisor(logdir=logdir, is_chief=False)
    with tf.Graph().as_default(), tf.device("/job:ps"):
      tf.Variable([1.0, 2.0, 3.0], name="v")
      tf.train.Supervisor(logdir=logdir, is_chief=False)

  def testDefaultGlobalStep(self):
    logdir = _test_dir("default_global_step")
    with tf.Graph().as_default():
      tf.Variable(287, name="global_step")
      sv = tf.train.Supervisor(logdir=logdir)
      sess = sv.prepare_or_wait_for_session("")
      self.assertEquals(287, sess.run(sv.global_step))
      sv.stop()

  def testRestoreFromMetaGraph(self):
    logdir = _test_dir("restore_from_meta_graph")
    with tf.Graph().as_default():
      tf.Variable(1, name="v0")
      sv = tf.train.Supervisor(logdir=logdir)
      sess = sv.prepare_or_wait_for_session("")
      filename = sv.saver.save(sess, sv.save_path)
      sv.stop()
    # Create a new Graph and Supervisor and recover.
    with tf.Graph().as_default():
      new_saver = tf.train.import_meta_graph(".".join([filename, "meta"]))
      self.assertIsNotNone(new_saver)
      sv2 = tf.train.Supervisor(logdir=logdir, saver=new_saver)
      sess = sv2.prepare_or_wait_for_session("")
      self.assertEquals(1, sess.run("v0:0"))
      sv2.saver.save(sess, sv2.save_path)
      sv2.stop()

  # This test is based on the fact that the standard services start
  # right away and get to run once before sv.stop() returns.
  # We still sleep a bit to make the test robust.
  def testStandardServicesWithoutGlobalStep(self):
    logdir = _test_dir("standard_services_without_global_step")
    # Create a checkpoint.
    with tf.Graph().as_default():
      v = tf.Variable([1.0], name="foo")
      tf.summary.scalar("v", v[0])
      sv = tf.train.Supervisor(logdir=logdir)
      meta_graph_def = meta_graph.create_meta_graph_def(
          saver_def=sv.saver.saver_def)
      sess = sv.prepare_or_wait_for_session("")
      save_path = sv.save_path
      self._wait_for_glob(save_path, 3.0)
      self._wait_for_glob(
          os.path.join(logdir, "*events*"), 3.0, for_checkpoint=False)
      # Wait to make sure everything is written to file before stopping.
      time.sleep(1)
      sv.stop()
    # There should be an event file with a version number.
    rr = _summary_iterator(logdir)
    ev = next(rr)
    self.assertEquals("brain.Event:2", ev.file_version)
    ev = next(rr)
    ev_graph = tf.GraphDef()
    ev_graph.ParseFromString(ev.graph_def)
    self.assertProtoEquals(sess.graph.as_graph_def(add_shapes=True), ev_graph)

    # Stored MetaGraphDef
    ev = next(rr)
    ev_meta_graph = meta_graph_pb2.MetaGraphDef()
    ev_meta_graph.ParseFromString(ev.meta_graph_def)
    self.assertProtoEquals(meta_graph_def, ev_meta_graph)
    self.assertProtoEquals(
        sess.graph.as_graph_def(add_shapes=True), ev_meta_graph.graph_def)

    ev = next(rr)
    self.assertProtoEquals("value { tag: 'v' simple_value: 1.0 }", ev.summary)

    ev = next(rr)
    self.assertEquals(tf.SessionLog.STOP, ev.session_log.status)

    self.assertRaises(StopIteration, lambda: next(rr))
    # There should be a checkpoint file with the variable "foo"
    with tf.Graph().as_default(), self.test_session() as sess:
      v = tf.Variable([10.10], name="foo")
      sav = tf.train.Saver([v])
      sav.restore(sess, save_path)
      self.assertEqual(1.0, v.eval()[0])

  # Same as testStandardServicesNoGlobalStep but with a global step.
  # We should get a summary about the step time.
  def testStandardServicesWithGlobalStep(self):
    logdir = _test_dir("standard_services_with_global_step")
    # Create a checkpoint.
    with tf.Graph().as_default():
      v = tf.Variable([123], name="global_step")
      sv = tf.train.Supervisor(logdir=logdir)
      meta_graph_def = meta_graph.create_meta_graph_def(
          saver_def=sv.saver.saver_def)
      sess = sv.prepare_or_wait_for_session("")
      # This is where the checkpoint will appear, with step number 123.
      save_path = "%s-123" % sv.save_path
      self._wait_for_glob(save_path, 3.0)
      self._wait_for_glob(
          os.path.join(logdir, "*events*"), 3.0, for_checkpoint=False)
      # Wait to make sure everything is written to file before stopping.
      time.sleep(1)
      sv.stop()
    # There should be an event file with a version number.
    rr = _summary_iterator(logdir)
    ev = next(rr)
    self.assertEquals("brain.Event:2", ev.file_version)
    ev = next(rr)
    ev_graph = tf.GraphDef()
    ev_graph.ParseFromString(ev.graph_def)
    self.assertProtoEquals(sess.graph.as_graph_def(add_shapes=True), ev_graph)
    ev = next(rr)
    ev_meta_graph = meta_graph_pb2.MetaGraphDef()
    ev_meta_graph.ParseFromString(ev.meta_graph_def)
    self.assertProtoEquals(meta_graph_def, ev_meta_graph)
    self.assertProtoEquals(
        sess.graph.as_graph_def(add_shapes=True), ev_meta_graph.graph_def)
    ev = next(rr)
    # It is actually undeterministic whether SessionLog.START gets written
    # before the summary or the checkpoint, but this works when run 10000 times.
    self.assertEquals(123, ev.step)
    self.assertEquals(tf.SessionLog.START, ev.session_log.status)
    first = next(rr)
    second = next(rr)
    # It is undeterministic whether the value gets written before the checkpoint
    # since they are on separate threads, so we check for both conditions.
    if first.HasField("summary"):
      self.assertProtoEquals("""value { tag: 'global_step/sec'
                                        simple_value: 0.0 }""",
                             first.summary)
      self.assertEquals(123, second.step)
      self.assertEquals(tf.SessionLog.CHECKPOINT, second.session_log.status)
    else:
      self.assertEquals(123, first.step)
      self.assertEquals(tf.SessionLog.CHECKPOINT, first.session_log.status)
      self.assertProtoEquals("""value { tag: 'global_step/sec'
                                        simple_value: 0.0 }""",
                             second.summary)
    ev = next(rr)
    self.assertEquals(tf.SessionLog.STOP, ev.session_log.status)
    self.assertRaises(StopIteration, lambda: next(rr))
    # There should be a checkpoint file with the variable "foo"
    with tf.Graph().as_default(), self.test_session() as sess:
      v = tf.Variable([-12], name="global_step")
      sav = tf.train.Saver([v])
      sav.restore(sess, save_path)
      self.assertEqual(123, v.eval()[0])

  def testNoQueueRunners(self):
    with tf.Graph().as_default(), self.test_session() as sess:
      sv = tf.train.Supervisor(logdir=_test_dir("no_queue_runners"))
      self.assertEqual(0, len(sv.start_queue_runners(sess)))
      sv.stop()

  def testPrepareSessionAfterStopForChief(self):
    logdir = _test_dir("prepare_after_stop_chief")
    with tf.Graph().as_default():
      sv = tf.train.Supervisor(logdir=logdir, is_chief=True)

      # Create a first session and then stop.
      sess = sv.prepare_or_wait_for_session("")
      sv.stop()
      sess.close()
      self.assertTrue(sv.should_stop())

      # Now create a second session and test that we don't stay stopped, until
      # we ask to stop again.
      sess2 = sv.prepare_or_wait_for_session("")
      self.assertFalse(sv.should_stop())
      sv.stop()
      sess2.close()
      self.assertTrue(sv.should_stop())

  def testPrepareSessionAfterStopForNonChief(self):
    logdir = _test_dir("prepare_after_stop_nonchief")
    with tf.Graph().as_default():
      sv = tf.train.Supervisor(logdir=logdir, is_chief=False)

      # Create a first session and then stop.
      sess = sv.prepare_or_wait_for_session("")
      sv.stop()
      sess.close()
      self.assertTrue(sv.should_stop())

      # Now create a second session and test that we don't stay stopped, until
      # we ask to stop again.
      sess2 = sv.prepare_or_wait_for_session("")
      self.assertFalse(sv.should_stop())
      sv.stop()
      sess2.close()
      self.assertTrue(sv.should_stop())


if __name__ == "__main__":
  tf.test.main()