1# Copyright 2023 The TensorFlow Authors. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ==============================================================================
15# pylint: disable=unidiomatic-typecheck
16"""Eager semantics for polymorphic function."""
17
18from tensorflow.python.util.tf_export import tf_export
19
20
21RUN_FUNCTIONS_EAGERLY = False
22
23
24@tf_export("config.functions_run_eagerly")
25def functions_run_eagerly():
26 """Returns the value of the `run_functions_eagerly` setting."""
27 return RUN_FUNCTIONS_EAGERLY
28
29
30@tf_export("config.run_functions_eagerly")
31def run_functions_eagerly(run_eagerly):
32 """Enables / disables eager execution of `tf.function`s.
33
34 Calling `tf.config.run_functions_eagerly(True)` will make all
35 invocations of `tf.function` run eagerly instead of running as a traced graph
36 function. This can be useful for debugging. As the code now runs line-by-line,
37 you can add arbitrary `print` messages or pdb breakpoints to monitor the
38 inputs/outputs of each Tensorflow operation. However, you should avoid using
39 this for actual production because it significantly slows down execution.
40
41 >>> def my_func(a):
42 ... print(f'a: {a}')
43 ... return a + a
44 >>> a_fn = tf.function(my_func)
45
46 >>> # A side effect the first time the function is traced
47 >>> # In tracing time, `a` is printed with shape and dtype only
48 >>> a_fn(tf.constant(1))
49 a: Tensor("a:0", shape=(), dtype=int32)
50 <tf.Tensor: shape=(), dtype=int32, numpy=2>
51
52 >>> # `print` is a python side effect, it won't execute as the traced function
53 >>> # is called
54 >>> a_fn(tf.constant(2))
55 <tf.Tensor: shape=(), dtype=int32, numpy=4>
56
57 >>> # Now, switch to eager running
58 >>> tf.config.run_functions_eagerly(True)
59 >>> # The code now runs eagerly and the actual value of `a` is printed
60 >>> a_fn(tf.constant(2))
61 a: 2
62 <tf.Tensor: shape=(), dtype=int32, numpy=4>
63
64 >>> # Turn this back off
65 >>> tf.config.run_functions_eagerly(False)
66
67 Note: This flag has no effect on functions passed into tf.data transformations
68 as arguments. tf.data functions are never executed eagerly and are always
69 executed as a compiled Tensorflow Graph.
70
71 Args:
72 run_eagerly: Boolean. Whether to run functions eagerly.
73 """
74 global RUN_FUNCTIONS_EAGERLY
75 RUN_FUNCTIONS_EAGERLY = bool(run_eagerly)