Пример #1
0
def node_to_graph(node, ctx, nocompile_decorators):
    """Convert Python code to equivalent TF graph mode code.

  Args:
    node: A Python AST node representing the code to convert.
    ctx: An EntityContext object.
    nocompile_decorators: A tuple containing decorators to be stripped from
        functions during conversion.

  Returns:
    A tuple (node, deps):
        * node: A Python ast node, representing the converted code.
        * deps: A set of strings, the fully qualified names of entity
            dependencies that this node has.
  """
    # TODO(mdan): Verify arguments for correctness.

    # TODO(mdan): Factor out common elements.
    # These include:
    #   * code move between blocks
    #   * visiting blocks in transformers

    # Certain steps, especially canonicalization, insert new symbols into the
    # tree, which must be accounted. Although less efficient, it is most robust
    # to re-run the analysis.

    node = _static_analysis_pass(node, ctx)
    # Past this point, line numbers are no longer accurate so we ignore the
    # source.
    # TODO(mdan): Is it feasible to reconstruct intermediate source code?
    ctx.source_code = None
    node = decorators.transform(node, nocompile_decorators)
    node = break_statements.transform(node, ctx)
    node = asserts.transform(node, ctx)

    # Note: sequencing continue canonicalization before for loop one avoids
    # dealing with the extra loop increment operation that the for
    # canonicalization creates.
    node = continue_statements.transform(node, ctx)
    ctx.namespace['len'] = len

    node = _static_analysis_pass(node, ctx)
    node = for_loops.transform(node, ctx)
    # for_loops may insert new global references.
    node = builtin_functions.transform(node, ctx)
    # TODO(mdan): Kept for CL consistency. Remove.
    # builtin_functions may insert new global references.
    ctx.namespace['print'] = print

    node = _static_analysis_pass(node, ctx)
    node = call_trees.transform(node, ctx, config.DEFAULT_UNCOMPILED_MODULES,
                                nocompile_decorators)
    node = control_flow.transform(node, ctx)

    # control_flow may create new symbols and change scopes.
    node = _static_analysis_pass(node, ctx)
    node = logical_expressions.transform(node)
    node = side_effect_guards.transform(node, ctx)

    return node
Пример #2
0
def node_to_graph(node, ctx, nocompile_decorators):
  """Convert Python code to equivalent TF graph mode code.

  Args:
    node: A Python AST node representing the code to convert.
    ctx: An EntityContext object.
    nocompile_decorators: A tuple containing decorators to be stripped from
        functions during conversion.

  Returns:
    A tuple (node, deps):
        * node: A Python ast node, representing the converted code.
        * deps: A set of strings, the fully qualified names of entity
            dependencies that this node has.
  """
  # TODO(mdan): Verify arguments for correctness.

  # TODO(mdan): Factor out common elements.
  # These include:
  #   * code move between blocks
  #   * visiting blocks in transformers

  # Certain steps, especially canonicalization, insert new symbols into the
  # tree, which must be accounted. Although less efficient, it is most robust
  # to re-run the analysis.

  node = _static_analysis_pass(node, ctx)
  # Past this point, line numbers are no longer accurate so we ignore the
  # source.
  # TODO(mdan): Is it feasible to reconstruct intermediate source code?
  ctx.source_code = None
  node = decorators.transform(node, nocompile_decorators)
  node = break_canonicalization.transform(node, ctx)
  node = asserts.transform(node, ctx)

  # Note: sequencing continue canonicalization before for loop one avoids
  # dealing with the extra loop increment operation that the for
  # canonicalization creates.
  node = continue_canonicalization.transform(node, ctx)
  ctx.namespace['len'] = len

  node = _static_analysis_pass(node, ctx)
  node = for_canonicalization.transform(node, ctx)
  # for_canonicalization may insert new global references.
  node = builtin_functions.transform(node, ctx)
  # builtin_functions may insert new global references.
  ctx.namespace['print'] = print

  node = _static_analysis_pass(node, ctx)
  node = call_trees.transform(node, ctx, config.DEFAULT_UNCOMPILED_MODULES,
                              nocompile_decorators)
  node = control_flow.transform(node, ctx)

  # control_flow may create new symbols and change scopes.
  node = _static_analysis_pass(node, ctx)
  node = logical_expressions.transform(node)
  node = side_effect_guards.transform(node, ctx)

  return node
Пример #3
0
def node_to_graph(node, ctx, nocompile_decorators):
  """Convert Python code to equivalent TF graph mode code.

  Args:
    node: A Python AST node representing the code to convert.
    ctx: An EntityContext object.
    nocompile_decorators: A tuple containing decorators to be stripped from
        functions during conversion.

  Returns:
    A tuple (node, deps):
        * node: A Python ast node, representing the converted code.
        * deps: A set of strings, the fully qualified names of entity
            dependencies that this node has.
  """
  # TODO(mdan): Verify arguments for correctness.

  # TODO(mdan): Factor out common elements.
  # These include:
  #   * keeping track of symbols that have been created
  #   * marking nodes (e.g. py_func wrappers) to suppress further processing
  #   * code move between blocks
  #   * insertion of new global references
  #   * visiting blocks in transformers

  # Certain steps, especially canonicalization, insert new symbols into the
  # tree, which must be accounted. Although less efficient, it is most robust
  # to re-run the analysis.

  node = _static_analysis_pass(node, ctx)
  node = decorators.transform(node, nocompile_decorators)
  node = break_canonicalization.transform(node, ctx.namer)

  # Note: sequencing continue canonicalization before for loop one avoids
  # dealing with the extra loop increment operation that the for
  # canonicalization creates.
  node = continue_canonicalization.transform(node, ctx.namer)
  ctx.namespace['len'] = len

  node = _static_analysis_pass(node, ctx)
  node = for_canonicalization.transform(node, ctx.namer)
  # for_canonicalization may insert new global references.
  node = builtin_functions.transform(node)
  # builtin_functions may insert new global references.
  ctx.namespace['print'] = print

  node = _static_analysis_pass(node, ctx)
  node = print_functions.transform(node)
  node = call_trees.transform(node, ctx.namer, ctx.namespace,
                              config.DEFAULT_UNCOMPILED_MODULES,
                              nocompile_decorators)
  node = control_flow.transform(node, ctx.namer)
  node = logical_expressions.transform(node)
  node = side_effect_guards.transform(node, ctx.namer)

  return node
Пример #4
0
    def test_transform(self):
        def test_fn(a):
            state_ops.assign(a, a + 1)
            return a

        node = self.parse_and_analyze(test_fn, {'state_ops': state_ops})
        node = side_effect_guards.transform(node, TestNamer())
        result = compiler.ast_to_object(node)
        setattr(result, 'state_ops', state_ops)

        # TODO(mdan): Configure the namespaces instead of doing these hacks.
        ops.identity = array_ops.identity
        setattr(result, 'tf', ops)

        with self.test_session() as sess:
            v = variables.Variable(2)
            sess.run(v.initializer)
            self.assertEqual(3, sess.run(result.test_fn(v)))
 def _transform_and_compile(self, test_fn):
   ns = {
       'control_flow_ops': control_flow_ops,
       'constant_op': constant_op,
       'gen_math_ops': gen_math_ops,
       'ops': ops,
       'state_ops': state_ops,
   }
   node = self.parse_and_analyze(
       test_fn, ns,
       namer=TestNamer())
   node = side_effect_guards.transform(node, self.ctx)
   result = compiler.ast_to_object(node)
   self.attach_namespace(result, **ns)
   result.tf = self.make_fake_tf(array_ops.identity, control_flow_ops.Assert,
                                 gen_math_ops.greater,
                                 ops.control_dependencies, ops.Tensor)
   result.py2tf_utils = utils
   return result.test_fn, node
Пример #6
0
    def test_side_effect_on_tensor(self):

        tf = None

        def test_fn(a):
            tf.Assert(a > 0, ['expected in throw'])
            return a

        node = self.parse_and_analyze(test_fn, {})
        node = side_effect_guards.transform(node, self.ctx)

        with self.compiled(node, control_flow_ops.Assert) as result:
            self.assertEqual(len(node.body[0].body), 1)
            with self.test_session() as sess:
                # NOTE: In this case we can also capture the side effect because the
                # argument is a tensor ans we can wrap it inside an identity.
                with self.assertRaisesRegexp(errors_impl.InvalidArgumentError,
                                             'expected in throw'):
                    sess.run(result.test_fn(constant_op.constant(-1)))
Пример #7
0
    def test_side_effect_on_return_only_variable(self):

        tf = None

        def test_fn(a):
            tf.assign(a, a + 1)
            return a

        node = self.parse_and_analyze(test_fn, {})
        node = side_effect_guards.transform(node, self.ctx)

        with self.compiled(node, state_ops.assign) as result:
            self.assertEqual(len(node.body[0].body), 1)
            with self.test_session() as sess:
                v = variables.Variable(2)
                sess.run(v.initializer)
                # NOTE: We don't expect the assignment to execute in this case, because
                # variables cannot be reliably guarded.
                self.assertEqual(2, sess.run(result.test_fn(v)))
Пример #8
0
  def test_transform(self):

    def test_fn(a):
      state_ops.assign(a, a + 1)
      return a

    node = self.parse_and_analyze(test_fn, {'state_ops': state_ops})
    node = side_effect_guards.transform(node, TestNamer())
    result = compiler.ast_to_object(node)
    setattr(result, 'state_ops', state_ops)

    # TODO(mdan): Configure the namespaces instead of doing these hacks.
    ops.identity = array_ops.identity
    setattr(result, 'tf', ops)

    with self.test_session() as sess:
      v = variables.Variable(2)
      sess.run(v.initializer)
      self.assertEqual(3, sess.run(result.test_fn(v)))
  def test_side_effect_on_tensor(self):

    tf = None

    def test_fn(a):
      tf.Assert(a > 0, ['expected in throw'])
      return a

    node = self.parse_and_analyze(test_fn, {})
    node = side_effect_guards.transform(node, self.ctx)

    with self.compiled(node, control_flow_ops.Assert) as result:
      self.assertEqual(len(node.body[0].body), 1)
      with self.test_session() as sess:
        # NOTE: In this case we can also capture the side effect because the
        # argument is a tensor ans we can wrap it inside an identity.
        with self.assertRaisesRegexp(errors_impl.InvalidArgumentError,
                                     'expected in throw'):
          sess.run(result.test_fn(constant_op.constant(-1)))
  def test_side_effect_on_return_only_variable(self):

    tf = None

    def test_fn(a):
      tf.assign(a, a + 1)
      return a

    node = self.parse_and_analyze(test_fn, {})
    node = side_effect_guards.transform(node, self.ctx)

    with self.compiled(node, state_ops.assign) as result:
      self.assertEqual(len(node.body[0].body), 1)
      with self.test_session() as sess:
        v = variables.Variable(2)
        sess.run(v.initializer)
        # NOTE: We don't expect the assignment to execute in this case, because
        # variables cannot be reliably guarded.
        self.assertEqual(2, sess.run(result.test_fn(v)))
Пример #11
0
    def test_side_effect_on_used_variable(self):

        tf = None

        def test_fn(a):
            tf.assign(a, a + 1)
            return a + 1

        node = self.parse_and_analyze(test_fn, {})
        node = side_effect_guards.transform(node, self.ctx)

        with self.compiled(node, state_ops.assign) as result:
            self.assertEqual(len(node.body[0].body), 1)
            with self.test_session() as sess:
                v = variables.Variable(2)
                sess.run(v.initializer)
                # NOTE: Unlike test_side_effect_on_return_only_variable, the variable
                # was used in the local scope and so we could catch the assign's side
                # effect.
                self.assertEqual(4, sess.run(result.test_fn(v)))
  def test_side_effect_on_used_variable(self):

    tf = None

    def test_fn(a):
      tf.assign(a, a + 1)
      return a + 1

    node = self.parse_and_analyze(test_fn, {})
    node = side_effect_guards.transform(node, self.ctx)

    with self.compiled(node, state_ops.assign) as result:
      self.assertEqual(len(node.body[0].body), 1)
      with self.test_session() as sess:
        v = variables.Variable(2)
        sess.run(v.initializer)
        # NOTE: Unlike test_side_effect_on_return_only_variable, the variable
        # was used in the local scope and so we could catch the assign's side
        # effect.
        self.assertEqual(4, sess.run(result.test_fn(v)))
Пример #13
0
    def test_multiline_block(self):

        tf = None

        def test_fn(a):
            tf.assign(a, a + 1)
            b = a + 1
            tf.assign(a, b + 1)
            c = b + 1
            d = c + 1
            return d

        node = self.parse_and_analyze(test_fn, {})
        node = side_effect_guards.transform(node, self.ctx)

        with self.compiled(node, state_ops.assign) as result:
            self.assertEqual(len(node.body[0].body), 1)
            with self.test_session() as sess:
                v = variables.Variable(2)
                sess.run(v.initializer)
                self.assertEqual(6, sess.run(result.test_fn(v)))
  def test_multiline_block(self):

    tf = None

    def test_fn(a):
      tf.assign(a, a + 1)
      b = a + 1
      tf.assign(a, b + 1)
      c = b + 1
      d = c + 1
      return d

    node = self.parse_and_analyze(test_fn, {})
    node = side_effect_guards.transform(node, self.ctx)

    with self.compiled(node, state_ops.assign) as result:
      self.assertEqual(len(node.body[0].body), 1)
      with self.test_session() as sess:
        v = variables.Variable(2)
        sess.run(v.initializer)
        self.assertEqual(6, sess.run(result.test_fn(v)))
Пример #15
0
    def test_multiline_block_unsafe(self):

        tf = None

        def test_fn(a):
            tf.assign(a, a + 1)
            b = a + 1
            tf.assign(a, a + 1)
            c = b + 1
            d = c + 1
            return d

        node = self.parse_and_analyze(test_fn, {})
        node = side_effect_guards.transform(node, self.ctx)

        with self.compiled(node, state_ops.assign) as result:
            self.assertEqual(len(node.body[0].body), 1)
            with self.test_session() as sess:
                v = variables.Variable(2)
                sess.run(v.initializer)
                # NOTE: This intentionally highlights the flakiness. The test should be
                # tightened down once that is solved.
                self.assertTrue(sess.run(result.test_fn(v)) in (6, 7))
  def test_multiline_block_unsafe(self):

    tf = None

    def test_fn(a):
      tf.assign(a, a + 1)
      b = a + 1
      tf.assign(a, a + 1)
      c = b + 1
      d = c + 1
      return d

    node = self.parse_and_analyze(test_fn, {})
    node = side_effect_guards.transform(node, self.ctx)

    with self.compiled(node, state_ops.assign) as result:
      self.assertEqual(len(node.body[0].body), 1)
      with self.test_session() as sess:
        v = variables.Variable(2)
        sess.run(v.initializer)
        # NOTE: This intentionally highlights the flakiness. The test should be
        # tightened down once that is solved.
        self.assertTrue(sess.run(result.test_fn(v)) in (6, 7))