传递tensor张量,当dtype、shape不变时,只会第一次触发跟踪
由@tf.function修饰的函数,多次调用该函数,传递不同的tensor张量,当dtype、shape不变时,只会第一次 触发跟踪,并创建图(下面介绍)
执行下面代码:
@tf.function
def f(a):
print("trace::",a)
tf.print("a::",a)
测试下面代码:
# 第一次执行会触发跟踪 f(tf.constant(1)) print("="*50) # 再次执行,当dtype、shape不变时,不会触发跟踪 f(tf.constant(2))执行结果:
trace:: Tensor("a:0", shape=(), dtype=int32) a:: 1 ================================================== a:: 2测试下面代码:
# 由于dtype是float32,所以会触发跟踪 f(tf.constant(3.0)) print("="*50) # 由于shape是(1,),所以会触发跟踪 f(tf.constant([3.0]))执行结果:
trace:: Tensor("a:0", shape=(), dtype=float32) a:: 3 ================================================== trace:: Tensor("a:0", shape=(1,), dtype=float32) a:: [3]
传递tensor张量,当dtype、shape不变时,只会第一次创建图
由@tf.function修饰的函数,多次调用该函数,传递不同的tensor张量,当dtype、shape不变时,只会第一次 创建图
通过get_concrete_function()方式获取创建的图
测试下面代码
# 第一次会创建图 print(f.get_concrete_function(tf.constant(1)).graph) # 再次调用,由于tensor的dtype和shape不变,所以不会创建图 print(f.get_concrete_function(tf.constant(2)).graph)执行结果:
trace:: Tensor("a:0", shape=(), dtype=int32) FuncGraph(name=f, id=5184009104) FuncGraph(name=f, id=5184009104)从id可知,图是相同的
测试下面代码
# 由于tensor的dtype改变,所以会触发跟踪,并创建图 print(f.get_concrete_function(tf.constant(3.0)).graph) # 由于tensor的shape改变,所以会触发跟踪,并创建图 print(f.get_concrete_function(tf.constant([4,5])).graph)执行结果:
trace:: Tensor("a:0", shape=(), dtype=float32) FuncGraph(name=f, id=5183546320) trace:: Tensor("a:0", shape=(2,), dtype=int32) FuncGraph(name=f, id=5186067216)从id可知,这是创建2个图