tensorflow icon indicating copy to clipboard operation
tensorflow copied to clipboard

tf.train.string_input_producer breaks when num_epochs is set

Open bcarpenter-pub opened this issue 10 years ago • 29 comments

I'm using a tf.train.string_input_producer to read in data from a file. when I set num_epochs=1 instead of None it breaks and I get the following error. My code is below as well.

Any suggestions for why this is occuring?

I tensorflow/core/common_runtime/local_device.cc:40] Local device intra op parallelism threads: 8
I tensorflow/core/common_runtime/direct_session.cc:58] Direct session inter op parallelism threads: 8
W tensorflow/core/common_runtime/executor.cc:1076] 0x7fdc4ba6b0f0 Compute status: Out of range: RandomShuffleQueue '_2_shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 10, current size 0)
     [[Node: shuffle_batch = QueueDequeueMany[component_types=[DT_FLOAT, DT_FLOAT], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](shuffle_batch/random_shuffle_queue, shuffle_batch/n)]]
W tensorflow/core/common_runtime/executor.cc:1076] 0x7fdc48da9170 Compute status: Out of range: FIFOQueue '_0_file_queue' is closed and has insufficient elements (requested 1, current size 0)
     [[Node: ReaderRead = ReaderRead[_device="/job:localhost/replica:0/task:0/cpu:0"](TFRecordReader, file_queue)]]
W tensorflow/core/common_runtime/executor.cc:1076] 0x7fdc4b8dbe20 Compute status: Aborted: Queue '_2_shuffle_batch/random_shuffle_queue' is already closed.
     [[Node: shuffle_batch/random_shuffle_queue_Close = QueueClose[cancel_pending_enqueues=false, _device="/job:localhost/replica:0/task:0/cpu:0"](shuffle_batch/random_shuffle_queue)]]
Traceback (most recent call last):
  File "tensorflow_test.py", line 51, in <module>
    coord.join(threads)
  File "/Users/blakec/virtual_envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/training/coordinator.py", line 205, in join
    six.reraise(*self._exc_info_to_raise)
  File "/Users/blakec/virtual_envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/training/queue_runner.py", line 112, in _run
    sess.run(enqueue_op)
  File "/Users/blakec/virtual_envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 368, in run
    results = self._do_run(target_list, unique_fetch_targets, feed_dict_string)
  File "/Users/blakec/virtual_envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 444, in _do_run
    e.code)
tensorflow.python.framework.errors.FailedPreconditionError: Attempting to use uninitialized value file_queue/limit_epochs/epochs
     [[Node: file_queue/limit_epochs/CountUpTo = CountUpTo[T=DT_INT64, limit=2, _device="/job:localhost/replica:0/task:0/cpu:0"](file_queue/limit_epochs/epochs)]]
Caused by op u'file_queue/limit_epochs/CountUpTo', defined at:
  File "tensorflow_test.py", line 6, in <module>
    filename_queue = tf.train.string_input_producer(["datasets_top_10_50k/VALIDATION_testset/part-00000..tf"], num_epochs=2,capacity=10000, name="file_queue")
  File "/Users/blakec/virtual_envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/training/input.py", line 135, in string_input_producer
    "fraction_of_%d_full" % capacity)
  File "/Users/blakec/virtual_envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/training/input.py", line 86, in _input_producer
    input_tensor = limit_epochs(input_tensor, num_epochs)
  File "/Users/blakec/virtual_envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/training/input.py", line 77, in limit_epochs
    counter = epochs.count_up_to(num_epochs)
  File "/Users/blakec/virtual_envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/variables.py", line 414, in count_up_to
    return state_ops.count_up_to(self._variable, limit=limit)
  File "/Users/blakec/virtual_envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/gen_state_ops.py", line 110, in count_up_to
    return _op_def_lib.apply_op("CountUpTo", ref=ref, limit=limit, name=name)
  File "/Users/blakec/virtual_envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/op_def_library.py", line 664, in apply_op
    op_def=op_def)
  File "/Users/blakec/virtual_envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1834, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/Users/blakec/virtual_envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1043, in __init__
    self._traceback = _extract_stack()

Code:

import tensorflow as tf
import time

filename_queue = tf.train.string_input_producer(["datasets_top_10_50k/VALIDATION_testset/part-00000..tf"], num_epochs=2,capacity=10000, name="file_queue")
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)

data = tf.parse_single_example(
      serialized_example,
      dense_keys=["features","labels"],
      dense_types=[tf.float32, tf.float32],
      dense_shapes=[(4096),(10)])

features = data["features"]
labels = data["labels"]

batch_size=10
capacity=1000
min_after_dequeue=100
example_batch, label_batch = tf.train.shuffle_batch(
      [features, labels], 
      batch_size=batch_size, 
      capacity=capacity,
      min_after_dequeue=min_after_dequeue)
num_examples = 0
with tf.Session() as sess:
    # Start populating the filename queue.
    coord = tf.train.Coordinator()  
    threads = tf.train.start_queue_runners(coord=coord, sess=sess)

    try:
        step = 0
        while not coord.should_stop():
            start_time = time.time()
            e, l = sess.run([example_batch, label_batch])
            print "grabbing"
            e, l = sess.run([example_batch, label_batch])
            num_examples = num_examples + e.shape[0]
            print "num_examples = " + str(num_examples)
            duration = time.time() - start_time

    except tf.errors.OutOfRangeError:
        print('Done training for %d epochs, %d steps.' % (FLAGS.num_epochs, step))
    finally:
        # When done, ask the threads to stop.
        coord.request_stop()

        # Wait for threads to finish.
        coord.join(threads)
        sess.close()

bcarpenter-pub avatar Feb 10 '16 21:02 bcarpenter-pub

This doesn't seem to be a bug in TensorFlow (are you running initialize_all_variables?), this kind of question is better for StackOverflow

yaroslavvb avatar Feb 11 '16 20:02 yaroslavvb

I have the same issue

ysfseu avatar May 19 '16 14:05 ysfseu

I had the same issue. But 'tf.initialize_all_variables()' solved it. This should be mentioned in the documentation or be considered as a bug.

timmeinhardt avatar Jul 06 '16 12:07 timmeinhardt

@timmeinhardt Thank you! your comment put me on the right track. However, I think the current master branch put the created variables into the LOCAL_VARIABLES collection, so i had to initialize with tf.initialize_local_variables() as well.

MycChiu avatar Jul 08 '16 11:07 MycChiu

local_variable can't be initialized by tf.initialize_all_variables()

suiyuan2009 avatar Aug 15 '16 12:08 suiyuan2009

I would never have been able to solve this problem if I hadn't found this issue. If tf.initialize_all_variables() doesn't initialize local variables, then there's either a bug in its implementation, a documentation issue (specifically, the word "all"), or both.

jlowin avatar Oct 04 '16 13:10 jlowin

Can someone elaborate why this got closed without resolving the confusion around initializing all and/or local variables? This should definitely be changed or documented accordingly!

I would be happy to make a PR with the necessary changes.

timmeinhardt avatar Oct 13 '16 08:10 timmeinhardt

Sorry, I shouldn't have closed it -- I mistakenly thought the problem was user forgetting to run initialize_all_variables, but the real issue is that a new class of variables was added that's not part of all_variables, but still needs to be initialized. I'm not sure there's an easy way to salvage the meaning of all in all_variables, @vrv may have more context on this

yaroslavvb avatar Oct 13 '16 17:10 yaroslavvb

There some some talk of a deprecation of "all" so that initialize_all_variables would be replaced with initialize_$something_variables, but the name was never settled on. It's also going to be hard since nearly every program in TF uses initialize_all_variables().

Assigning to those who have thought about this more.

vrv avatar Oct 13 '16 17:10 vrv

From the opposite point of view there are probably only very few cases where somebody calls 'initialize_all_variables' and does not want to initialise all variables including the local variables. To ensure backwards compatibility I think 'initialize_all_variables' should be kept and do what its name suggests.

But I am curious to hear what more experienced tensorflowers might have to say!

timmeinhardt avatar Oct 13 '16 17:10 timmeinhardt

From my limited understanding, that's not the case: there was some low level library added that decided that its variables didn't want to be part of "all" because they are local to each replica of a model, and would break a ton of models if they were initiailzed along with "all". Hence the dilemma, and why this wasn't already done. In other words, "local" variables are explicitly not part of "all". Unfortunately, the name "all" was introduced well before this new use came in, so it's extremely sad and confusing.

vrv avatar Oct 13 '16 17:10 vrv

In this case, It seems like moving epoch counter to local variables was a fix for some issues in the tf.contrib.learn library. I think we can just add notes to the documentation on all input_producers' num_epochs parameter to remind users that they need to initialize with initialize_local_variables() if they want to limit the epochs.Like the ones in tf.contrib.learn.read_batch_features

MycChiu avatar Oct 14 '16 05:10 MycChiu

It feels very un-user-friendly to expect users to parse the documentation for a function that they may not even call directly (since it could be buried in a convenient utility function) while still having an initialize_all_variables() op that doesn't actually do what its name implies.

On the other hand, I totally understand why there are times that you would want your variables to be excluded from the global init_op and having local variables makes sense in that context. Based on what I've learned here, I believe the problem in this case is that 1) we need to initialize epochs but 2) we don't want to restore epochs when the model is loaded because we want to be able to run the model!

Is there a middle ground here? Maybe a way of marking a variable as not being restored? The whole issue feels to me like a very heavy-handed way of dancing around the problem.

jlowin avatar Oct 14 '16 16:10 jlowin

I thought one should only save the relevant model variables ,like the trainable ones and the moving moments if you use batch_norm, while using tf.train.Saver. If to avoid restoring epoch while restoring model is the only concern here, I think it would be better to just exclude epochs from the variables being saved.

However, I don't think this will prevent things from breaking in the distributed setting like @vrv mentioned.

For the time being, I think it would be really helpful to add the notes for now. (I could still feel the agony and pain from the hours I spent debugging this while violently scratching my head)

MycChiu avatar Oct 15 '16 05:10 MycChiu

Currently, there is still no decision on making it one way or another. @sherrym is responsible for finalizing this.

ilblackdragon avatar Oct 28 '16 04:10 ilblackdragon

@sherrym any decision on this?

drpngx avatar Jan 24 '17 01:01 drpngx

Just got bit by this issue as well. Thank $DEITY for Google search, the error spew is impenetrable. The fix for me was simply to change the usual init_op = tf.global_variables_initializer() to init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()), and run it when the Session is up.

ghost avatar Feb 15 '17 08:02 ghost

I still have this problem after I run tf.group(tf.local_variables_initializer(), tf.global_variables_initializer()) I use tensorflow r1.0. Anyone could help? Detailed trace back as follows:

Traceback (most recent call last): File "", line 1, in File "/home/dl/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 699, in runfile execfile(filename, namespace) File "/home/dl/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 81, in execfile builtins.execfile(filename, *where) File "/media/dl/data2/tf_projects/NUS/eval_mscoco.py", line 138, in coord.join(threads) File "/home/dl/anaconda/lib/python2.7/site-packages/tensorflow/python/training/coordinator.py", line 386, in join six.reraise(*self._exc_info_to_raise) File "/home/dl/anaconda/lib/python2.7/site-packages/tensorflow/python/training/queue_runner_impl.py", line 234, in _run sess.run(enqueue_op) File "/home/dl/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 767, in run run_metadata_ptr) File "/home/dl/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 965, in _run feed_dict_string, options, run_metadata) File "/home/dl/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1015, in _do_run target_list, options, run_metadata) File "/home/dl/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1035, in _do_call raise type(e)(node_def, op, message) tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value input_producer/input_producer/fraction_of_32_full/limit_epochs/epochs [[Node: input_producer/input_producer/fraction_of_32_full/limit_epochs/CountUpTo = CountUpToT=DT_INT64, _class=["loc:@input_producer/input_producer/fraction_of_32_full/limit_epochs/epochs"], limit=1, _device="/job:localhost/replica:0/task:0/cpu:0"]]

Caused by op u'input_producer/input_producer/fraction_of_32_full/limit_epochs/CountUpTo', defined at: File "", line 1, in File "/home/dl/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 699, in runfile execfile(filename, namespace) File "/home/dl/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 81, in execfile builtins.execfile(filename, *where) File "/media/dl/data2/tf_projects/NUS/eval_mscoco.py", line 46, in fns, labels = tf.train.slice_input_producer([fns, labels], num_epochs=1, shuffle=False) File "/home/dl/anaconda/lib/python2.7/site-packages/tensorflow/python/training/input.py", line 305, in slice_input_producer shared_name=shared_name) File "/home/dl/anaconda/lib/python2.7/site-packages/tensorflow/python/training/input.py", line 262, in range_input_producer shared_name, name, "fraction_of_%d_full" % capacity) File "/home/dl/anaconda/lib/python2.7/site-packages/tensorflow/python/training/input.py", line 156, in input_producer input_tensor = limit_epochs(input_tensor, num_epochs) File "/home/dl/anaconda/lib/python2.7/site-packages/tensorflow/python/training/input.py", line 96, in limit_epochs counter = epochs.count_up_to(num_epochs) File "/home/dl/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/variables.py", line 628, in count_up_to return state_ops.count_up_to(self._variable, limit=limit) File "/home/dl/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/gen_state_ops.py", line 126, in count_up_to result = _op_def_lib.apply_op("CountUpTo", ref=ref, limit=limit, name=name) File "/home/dl/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 763, in apply_op op_def=op_def) File "/home/dl/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2395, in create_op original_op=self._default_original_op, op_def=op_def) File "/home/dl/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1264, in init self._traceback = _extract_stack()

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value input_producer/input_producer/fraction_of_32_full/limit_epochs/epochs [[Node: input_producer/input_producer/fraction_of_32_full/limit_epochs/CountUpTo = CountUpToT=DT_INT64, _class=["loc:@input_producer/input_producer/fraction_of_32_full/limit_epochs/epochs"], limit=1, _device="/job:localhost/replica:0/task:0/cpu:0"]]

jiqiujia avatar Apr 16 '17 06:04 jiqiujia

@jiqiujia, I previously have the same problem. Later, I found that the local variables need to be initialized before any session starts; sometimes, the starting may be hidden in some other functions. In my case, it was "tf.train.start_queue_runners()"; when I put the initialization before that call, it will work well. Otherwise, there will be the same error as in your post. Hope it may help.

ybsave avatar Apr 24 '17 16:04 ybsave

@jiqiujia could you start the queue runners as suggested?

It does say input_producer.

drpngx avatar Apr 24 '17 20:04 drpngx