• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# AutoGraph reference
2
3[Index](index.md)
4
5## Generated code
6
7For each converted function, AutoGraph creates a new function. The
8loading mechanism is an implementation detail and may change, but the
9generated function is generally a regular
10[Python function](https://docs.python.org/3/reference/compound_stmts.html#function).
11This function is typically executed internally by `@tf.function` to construct a
12TensorFlow graph.
13
14### Transformations made to the generated code
15
16The generated code is a transformation of the input code. The transformations
17are listed below. Any other elements are left unchanged.
18
19Summary of transformations:
20
21 * function calls are replaced with a wrapper:
22   * `foo(args)` -> `ag__.converted_call(foo, args)`
23 * `if`, `while` and `for` statements are replaced with function calls:
24   * `if` -> `ag__.if_stmt`
25   * `while` -> `ag__.while_stmt`
26   * `for` -> `ag__.for_stmt`
27 * `break`, `return`, and `continue` statements are replaced with equivalent
28   `if` statements.
29 * `and`, `or` and `not` operators are replaced with function calls:
30   * `and` -> `ag__.and_`
31   * `or` -> `ag__.or_`
32   * `not` -> `ag__.not_`
33
34The functions replacing control flow statements are very similar in form with
35the corresponding control flow ops in TensorFlow.
36
37### AutoGraph generates normal Python code
38
39You can interact normally with the generated code. For example, you can use
40the `inspect.getsourcefile` and `inspect.getsource`:
41
42```
43def f(a):
44  ...
45
46converted_f = tf.autograph.to_graph(f)
47print(inspect.getsourcefile(converted_f))
48```
49```
50/tmp/tmpm562wlj7.py
51```
52
53When using `@tf.function`, you can repeat the same steps using the function's
54`python_function` attribute:
55
56```
57@tf.function
58def f(a):
59  ...
60
61converted_f = tf.autograph.to_graph(f.python_function)
62print(inspect.getsourcefile(converted_f))
63```
64```
65/tmp/tmpm562wlj7.py
66```
67
68`tf.autograph.to_code(f)` is a shortcut to obtain the generated code, and it's
69equivalent with calling `inspect.getsource(tf.autograph.to_graph(f))`.
70
71#### Recording diagnostic information: `tf.autograph.set_verbosity`
72
73AutoGraph can log additional debug information. This is mostly used for filing
74bugs, but can also be used to get an indication of whether a function is
75converted successfully or not.
76
77You can enable logging by calling `tf.autograph.set_verbosity(level)`. The
78`level` argument varies from 0 to 10:
79
80 * 0 - no logging
81 * 3 - includes the generated code
82 * 4 and above - extremely verbose logging
83
84Caution: The information being logged includes source code as well as
85data. Before sharing AutoGraph logs, make sure they don't contain any sensitive
86information.
87
88Alternatively, you can control the verbosity level using the environment
89variable `AUTOGRAPH_VERBOSITY`.
90