Skip to content

tf.import_graph_def() restricts the order of nodes in graph proto. #9906

Closed

Description

@sj6077

System information

  • Have I written custom code (as opposed to using a stock example script provided in TensorFlow): Yes
  • OS Platform and Distribution (e.g., Linux Ubuntu 16.04):
    Linux Ubuntu 14.04
  • TensorFlow installed from (source or binary):
    source
  • TensorFlow version (use command below):
    commit 3bee923
  • Bazel version (if compiling from source):
    0.4.5
  • CUDA/cuDNN version:
    cuda 8.0/cudnn 5.1.5
  • GPU model and memory:
    Tesla P40
  • Exact command to reproduce:

Describe the problem

I used auto parallel optimizer in grappler for cifar10 example, but grappler changes the order of nodes in graph proto. It causes the failure of import_graph_def, because ops.set_shapes_for_outputs(op), which is line 407 of tensorflow/tensorflow/python/framework/importer.py is failed. This is because all of the input nodes must be defined before to define a node. importer restricts the order of nodes for graph definition proto, but I think importer shoud be flexible to the order of nodes.

Source code / logs

with tf.Graph().as_default() as graph:
  #global_step = tf.contrib.framework.get_or_create_global_step()
  global_step = tf.get_variable(
      'global_step', [], dtype=tf.int32,
      initializer=tf.constant_initializer(0), trainable=False)

  # Get images and labels for CIFAR-10.
  images, labels = cifar10.distorted_inputs()

  # Build a Graph that computes the logits predictions from the
  # inference model.
  logits = cifar10.inference(images)

  # Calculate loss.
  loss = cifar10.loss(logits, labels)

  # Build a Graph that trains the model with one batch of examples and
  # updates the model parameters.
  train_op = cifar10.train(loss, global_step)

  init_op = tf.global_variables_initializer()

  queue_runners = []
  for qr in ops.get_collection(ops.GraphKeys.QUEUE_RUNNERS):
    queue_runners.append(qr.to_proto())

  mg = meta_graph.create_meta_graph_def(graph=graph)

#Auto-parallel
rewriter_config = rewriter_config_pb2.RewriterConfig()
rewriter_config.optimizers.append('autoparallel')
rewriter_config.auto_parallel.num_replicas = FLAGS.num_gpus

graph_def = tf_optimizer.OptimizeGraph(rewriter_config, mg)

with tf.Graph().as_default() as g:
  tf.import_graph_def(graph_def=graph_def, name='')

This is the log

 File "/cmsdata/ssd0/soojeong/tensorflow_venv/local/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "tensorflow_rdag/examples/distributed/cifar10/cifar10_in_graph_auto_parallel.py", line 157, in main
    train()
  File "tensorflow_rdag/examples/distributed/cifar10/cifar10_in_graph_auto_parallel.py", line 105, in train
    tf.import_graph_def(graph_def=graph_def, name='')
  File "/cmsdata/ssd0/soojeong/tensorflow_venv/local/lib/python2.7/site-packages/tensorflow/python/framework/importer.py", line 404, in import_graph_def
    ops.set_shapes_for_outputs(op)
  File "/cmsdata/ssd0/soojeong/tensorflow_venv/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1723, in set_shapes_for_outputs
    shapes = shape_func(op)
  File "/cmsdata/ssd0/soojeong/tensorflow_venv/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1673, in call_with_requiring
    return call_cpp_shape_fn(op, require_shape_fn=True)
  File "/cmsdata/ssd0/soojeong/tensorflow_venv/local/lib/python2.7/site-packages/tensorflow/python/framework/common_shapes.py", line 610, in call_cpp_shape_fn
    debug_python_shape_fn, require_shape_fn)
  File "/cmsdata/ssd0/soojeong/tensorflow_venv/local/lib/python2.7/site-packages/tensorflow/python/framework/common_shapes.py", line 653, in _call_cpp_shape_fn_impl
    v = tensor_util.constant_value(op.inputs[idx])
  File "/cmsdata/ssd0/soojeong/tensorflow_venv/local/lib/python2.7/site-packages/tensorflow/python/framework/tensor_util.py", line 710, in constant_value
    ret = _ConstantValue(tensor)
  File "/cmsdata/ssd0/soojeong/tensorflow_venv/local/lib/python2.7/site-packages/tensorflow/python/framework/tensor_util.py", line 676, in _ConstantValue
    fill_value = constant_value(tensor.op.inputs[1])
  File "/cmsdata/ssd0/soojeong/tensorflow_venv/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1443, in __getitem__
    return self._op._inputs[i]
IndexError: list index out of range

Activity

  1. concretevitamin commented on May 15, 2017

    @concretevitamin
    Contributor

    @benoitsteiner: mind taking a look? Do we have plans to modify tf.import_graph_def() for the desired effects?

  2. benoitsteiner commented on May 15, 2017

    @benoitsteiner
    Contributor

    The easiest solution is probably to update the grappler optimizers to ensure that the final output is generated in topological order. The one difficulty is going to figure out where to break looks to make TensorFlow happy. The natural place would be the NextIteration node.

  3. zhangyaobit commented on May 16, 2017

    @zhangyaobit

    @sj6077, it's great/exciting to see you are using this feature!

    While we are still actively developing it and improving its usability and scalability, I hit the same order problem you described when applying it to the RNN PTB model. I'm working on a fix to sort the nodes of an optimized graph in topological order, which will be submitted soon.

    We'd be glad to hear more of your feedback and suggestions later.

  4. sj6077 commented on May 17, 2017

    @sj6077
    ContributorAuthor

    Thank you. I'll look forward upgraded grappler optimizers!

  5. zhangyaobit commented on May 17, 2017

    @zhangyaobit

    The change (194b164) is in. Please give it a try.

  6. sj6077 commented on May 18, 2017

    @sj6077
    ContributorAuthor

    I tried, but there is another issue. I copied cifar10 model, but it doesn't utilize all the gpus. For example, conv2D is not copied for all gpus. I also got tensorflow/core/common_runtime/simple_placer.cc:668] Ignoring device specification /device:GPU:0 for node 'AutoParallel-Replica-0/GradientDescent' because the input edge from 'global_step_1' is a reference connection and already has a device field set to /device:GPU:2

    Can you give an example?

  7. zhangyaobit commented on May 18, 2017

    @zhangyaobit

    All transitive fanin nodes of target nodes should be copied/replicated for all GPUs. I think Conv2D is very likely to be in the transitive fanin and therefore should be replicated. Could you give more details on this and debug the AutoParallel code a bit to find out why it is not replicated?

    I'm aware of the simple_placer issue and will work on a fix. For now, a temporary workaround is
    config_proto = tf.ConfigProto(allow_soft_placement=True)

    Yes, I will submit an example on ptb RNN model soon.

  8. sj6077 commented on May 18, 2017

    @sj6077
    ContributorAuthor

    I'm not sure about Conv2D issue now, I'll figure out it more. I'm now trying to initialize variables, but I couldn't find an easy way. There are local3/weights/ExponentialMovingAverage/Assign_1 and local3/weights/ExponentialMovingAverage/Assign, I don't know what's the meaning.

    Another issue is queue_runner is not made for new operations, so with MonitoredTrainingSession, it doesn't work.

    Is it possible for multi-machines and multi-gpus? I want to add tf.train.SyncReplicasOptimizer somewhere.

    I'll wait for your example, but can you let me know about 2 issues related with initializer and queue runner before?

  9. zhangyaobit commented on May 18, 2017

    @zhangyaobit

    These two Assign nodes could be initializers for two variables. There are two collections in MetaGraphDef, "trainable_variables" and "variables", where you have a list of VariableDef including a field initializer_name for the corresponding initialization node. After you import the MetaGraphDef, these two collections should be preserved and you can run all initialization nodes in VariableDef.

    Could you be more specific about why queue_running doesn't work with MonitoredTrainingSession? Looks like MonitoredTrainingSession uses queue runner. https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/training/monitored_session.py#L541

    Yes, follow-up work will support multiple machines with both synchronous and async training; it may take some time for us to get there. For now, I'm not sure if using AutoParallel within a machine on multiple devices could be combined with a machine-level parallelization with SyncReplicasOptimizer; looks like they two should be compatible.

  10. sj6077 commented on May 19, 2017

    @sj6077
    ContributorAuthor

    Below is the code that I tried. The problem is collections in meta_graph is not updated for new graph from auto_parallel. So I can't access variables or queue_runner for new graph. Moreover, snapshot ops for variables, and operations of condition context collection are removed through auto_parallel.

     with tf.Graph().as_default():
        meta_graph_def = meta_graph_pb2.MetaGraphDef()
        meta_graph_def.ParseFromString(meta_graph_def_str)
        tf.import_meta_graph(meta_graph_def)
    
        rewriter_config = rewriter_config_pb2.RewriterConfig()
        rewriter_config.optimizers.append('autoparallel')
        rewriter_config.auto_parallel.num_replicas = num_replicas
    
        graph_def = tf_optimizer.OptimizeGraph(rewriter_config, meta_graph_def)
        tf.import_graph_def(graph_def=graph_def, name='')
    
        meta_graph_def = tf.train.export_meta_graph()
    
  11. zhangyaobit commented on May 19, 2017

    @zhangyaobit

    Yes, the collections are not updated and thus need manually updated currently. This is cumbersome and we will definitely think of ways to improve (will first get a working, proof-of-concept ptb example, and then improve/streamline the usage). In particular, you are exactly right that the snapshot name in VariableDef needs to be updated. For ptb, the names of all tensors (the states) that the model refer need to be updated (see the code below).

    I will just post the ptb_word_lm.py code below (before I submit it) for your reference. Could you try follow its usage pattern used here?

    https://gist.github.com/zhangyaobit/08c0b776e4b7a4f786714d46e723ee8a

  12. sj6077 commented on May 22, 2017

    @sj6077
    ContributorAuthor

    Thank you for your example! It's really helpful.

    I tested your example, but it has no speed up acrroding to the number of gpus increases. Is it just a problem of log?

    if verbose and step % (model.input.epoch_size // 10) == 10:
          print("%.3f perplexity: %.3f speed: %.0f wps" %
                (step * 1.0 / model.input.epoch_size, np.exp(costs / iters),
                 iters * model.input.batch_size / (time.time() - start_time)))
    
    
  13. zhangyaobit commented on May 22, 2017

    @zhangyaobit

    Yes, I believe it is a problem with logging. If you use tensorboard, you can compare global steps/sec and time to certain accuracy/loss.

  14. sj6077 commented on May 29, 2017

    @sj6077
    ContributorAuthor

    I found 2 issues related with auto-parallel.
    It doesn't replicate queues and euqueue ops, but if input pipeline contains a work for data-preprocessing, gpus are utilized as serial orders.
    One more thing is that apply gradient descent is a long time task, below is the tracing result, the computation time is less than 100ms but apply gradient descent takes more than 100ms. Is there any dpendencies between different apply gradient descent ops for same variables?

    2017-05-29 16 43 25

  15. zhangyaobit commented on May 31, 2017

    @zhangyaobit

    The queue and enqueue ops don't need to be replicated; only dequeue node is replicated, so that multiple GPUs could dequeue/work in parallel. If there is a lot of preprocessing for input data, you may consider using more threads for input preprocessing, so that it keeps up the GPU computations.

    The time for applying gradients depends on the models. For small models, it may become a bottleneck; for larger models like the PTB one, it takes relatively a small portion of total time, and you can expect about 1.7x speedup using 2 GPUs. Could you label each row in the picture, and name/mark the related ops?

  16. zhangyaobit commented on Sep 19, 2017

    @zhangyaobit

    Closing for now; feel free to reopen if needed.

  17. javacop01 commented on Oct 3, 2017

    @javacop01

    zhangyaobit,
    I know you seem to have fixed this issue with help from sj6077. I am seeing the same issue while running PTB example with tensorflow 1.2.1. Could you please confirm if these changes are already part of 1.2.1 release ? If not, what's the workaround ?

  18. zhangyaobit commented on Oct 4, 2017

    @zhangyaobit

    I took a look. This change is not in 1.2.1; it is in 1.3.0. Are you able to use 1.3.0?

    What's the error message do you see (could you post the stack trace)?

  19. JinScientist commented on Jan 9, 2018

    @JinScientist

    Hi zhangyaobit, I have tried with the ptb example with update collection utility, I still get this error under version 1.4.1

    Traceback

    (most recent call last):
    File "ppmodel.py", line 558, in
    tf.app.run()
    File "/home/ubuntu/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
    File "ppmodel.py", line 524, in main
    tf.train.import_meta_graph(metagraph)
    File "/home/ubuntu/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 1810, in import_meta_graph
    **kwargs)
    File "/home/ubuntu/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/meta_graph.py", line 696, in import_scoped_meta_graph
    ops.prepend_name_scope(value, scope_to_prepend_to_names))
    File "/home/ubuntu/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 3035, in as_graph_element
    return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
    File "/home/ubuntu/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 3077, in _as_graph_element_locked
    "graph." % (repr(name), repr(op_name)))
    KeyError: "The name 'Train/TrainInput/StridedSlice_1:0' refers to a Tensor which does not exist. The operation, 'Train/TrainInput/StridedSlice_1', does not exist in the graph."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions