TensorFlow: How can I evaluate a validation data queue multiple times during training?
<h2>tl;dr</h2>

<p>How can I evaluate a validation set after every K training iterations, using separate queues for training and validation data, without resorting to separate <code>tf.Sessions</code> in multiple processes? There doesn't seem to be a clean way to achieve this, given my particular problem, and my current workaround (which I thought would work) gives me undefined behavior. Help!</p>

<h2>The whole story</h2>

<p>I want to evaluate a validation set every K training iterations, and I cannot figure out how to implement this properly in TensorFlow. This should be one of the most common operations, yet it feels that TensorFlow's API/architecture is working against me here or is at least making things unnecessarily difficult.</p>

<p>My assumptions are:</p>

<ul>
<li>[A1] The multi-process model for training/validation as described here <a href="https://www.tensorflow.org/how_tos/reading_data/#multiple_input_pipelines" rel="noreferrer">https://www.tensorflow.org/how_tos/reading_data/#multiple_input_pipelines</a> is not applicable to my problem, as I have to assume there is not enough GPU memory available to load the variables twice.</li>
<li>[A2] I want to evaluate on the validation set every K training iterations.</li>
<li>[A3] Both training and validation data cannot be simply read from disk, but are generated on-the-fly. This makes it impossible to reliably pre-compute the size of the validation set in advance.</li>
<li>[A4] The validation set is too large to pre-compute and store onto disk.</li>
<li>[A5] The effective validation set size is not necessarily a multiple of the batch size.</li>
</ul>

<p>The training input pipeline is set up as follows:</p>

<ul>
<li>A <code>tf.train.slice_input_producer()</code> generates a (shuffled) list of filenames, each referring to raw input data.</li>
<li>A custom data generation function generates a variable number of training exemplars/labels from each chunk of raw input data.</li>
<li>The generated training exemplars/labels are queued via <code>tf.train.shuffle_batch()</code> before being fed into the network.</li>
</ul>

<p>Due to [A3], [A4], [A5], the validation input pipeline is set up in an almost identical way, except that the final input queue is generated via <code>tf.train.batch()</code>, since shuffling is not desirable. Due to the above assumptions, a feed_dict based approach is also infeasible, and also seemingly incompatible with using a higher level function such as <code>tf.train.batch</code>.</p>

<p>However, a straightforward implementation using two different sets of queues for training and validation does not work. As far as I understand, I have two options:</p>

<ul>
<li><p>[B1] Set the <code>num_epochs</code> argument of the validation <code>tf.train.slice_input_producer</code> to <code>None</code>.</p>

<p>In this case, the validation set is cycled through endlessly, but I would need to know the size of the validation set in advance to explicitly limit the number of batches to evaluate per run through the validation set. Furthermore, if the validation set size is not divisible by the batch size, I will always pull a bit more in the last batch. As this would shift the order of evaluation of the validation data each time, this is not acceptable.</p></li>
<li><p>[B2] Set the <code>num_epochs</code> argument of the validation <code>tf.train.slice_input_producer</code> to <code>1</code>, and additionally set the <code>allow_smaller_final_batch</code> argument of the <code>tf.train.batch</code> function to <code>True</code>.</p>

<p>In this case, the validation set is cycled through exactly once, after which the respective queue is closed forever. By default, this will make evaluating the validation set two or more times impossible. Since I do not know of a good way to reopen a queue in TensorFlow, I need to work around this limitation. </p></li>
</ul>

<p>Due to the greater limitations of option [B1], I chose to work around the issues of option [B2] instead. The (pseudo-)code outlining my current approach is as follows:</p>

<p>The training loop should be fairly canonical. Every K iterations, a function to evaluate the validation set is called.
Note that I only start the queues that have a name starting with "train_"; these is the queue set up for collecting generated training data. In order to do this, I created two helper functions, <code>get_queues_by_name</code> and <code>start_queue_runners</code>. </p>

<pre><code>def train_loop(train_ops, vali_ops, ...):
    with tf.Session() as sess:
        coord = tf.train.Coordinator()
        sess.run([tf.initialize_all_variables(), tf.initialize_local_variables()])
        load_latest_snapshot(sess, loader, snapshot_file)

        # Launch the queue runners
        queues = get_queues_by_name("train")
        threads = start_queue_runners(sess, coord, queues)

        try:
            for step in range(start_iteration, num_train_iterations):
                # Runs the session on validation set
                if step % K == 0:
                    validation_results = run_validation(vali_ops, snapshot_file)

                # TRAINING:
                # ...

        except Exception as e:
            coord.request_stop(e)
        finally:
            coord.request_stop()
            coord.join(threads)
</code></pre>

<p>The helper functions look like this:</p>

<pre><code>def get_queues_by_name(name):
    """Retrieves all queues that contain the string given by 'name'"""
    all_queues = tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS)
    return [q for q in all_queues if name in q.name]


def start_queue_runners(session, coordinator, queues):
    """Similar to tf.train.start_queue_runners but now accepts a list of queues instead of a graph collection"""
    with session.graph.as_default():
        threads = []
        for queue in queues:
            log("Queue", "Starting queue '%s'" % queue.name, level=2)
            threads.extend(queue.create_threads(session, coordinator, daemon=True, start=True))
    return threads
</code></pre>

<p>In the <code>run_validation</code> function, my chosen workaround against the issue of a closed queue is to create a new <code>tf.Session</code>. I also only start the threads associated with the queue collecting validation set data.</p>

<pre><code>def run_validation(ops, snapshot_file):  # Called inside train_loop()
    results = None
    loader = tf.train.Saver()

    with tf.Session() as sess:
        coord = tf.train.Coordinator()
        sess.run([tf.initialize_local_variables()])
        load_latest_snapshot(sess, loader, snapshot_file)

        # Launch the queue runners
        queues = get_queues_by_name("eval")
        threads = start_queue_runners(sess, coord, queues)

        # Performs the inference in batches
        try:
            # Evaluate validation set:
            results = eval_in_batches(ops, sess)
        except Exception as e:
            coord.request_stop(e)
        finally:
            coord.request_stop()
            coord.join(threads)

    return results
</code></pre>

<p>I do not know whether creating a new <code>tf.Session</code> here is a good idea, but it seems like the only way to accomplish restarting the validation queue. Ideally, I also wouldn't want to re-load the model snapshot, as this seems conceptually unnecessary.</p>

<p>The issue with this code is that I see erratic/undefined behavior during running, such as NaN's or Inf's appearing inside the network during validation set evaluation. This seems to occur predominantly when the validation set queue is being filled at the same time as the training set queue is still being filled (since the training queue is open during validation set evaluation). For example, this very often happens if I evaluate the validation set at iteration 0 (when both queues still need to be filled). It almost seems as if the training/validation queues share some global state, although they are running in a different session.</p>

<p>Can someone explain why this is happening, and how I can solve this more cleanly while taking my above assumptions [A1]-[A5] into account?</p>