推荐使用哪种混合TensorFlow和TensorFlow联合代码的方式?


问题内容

TensorFlow(TF)和TensorFlow Federated(TFF)是不同的功能层,旨在共同发挥作用(顾名思义)。

尽管如此,它们是旨在解决不同问题的不同事物。

我想知道以最佳方式描述计算的最佳方式是可以同时用于普通TF和TFF工作负载,以及人们可能希望避免的那种陷阱。


问题答案:

好问题。确实,至少有3种方法来处理与TFF一起使用的TensorFlow代码的组成,每种方法各有优点。

  1. 推荐使用TensorFlow的合成机制(defuns),前提是它适用于您的特定情况。TensorFlow已经拥有用于编写代码的机制,我们不想重新发明轮子。我们在TFF(@ tff.tf_computation)中创建了自己的合成机制的原因是为了应对特定的限制(例如,在TF的接口级别上缺乏对数据集的支持,以及TF组件需要与之互操作的原因) TFF的其余部分),那么我们最好将这种机制的使用限制在真正需要它的情况下。

如果可能,请使用@ tf.function装饰TensorFlow组件,然后将整个TensorFlow块仅在顶层包装为@
tff.tf_computation,然后再将其嵌入@
tff.federated_computation。它的众多好处之一是,它允许您使用标准的TensorFlow工具测试TFF之外的组件。

因此,鼓励并首选以下内容:

# here using TensorFlow's compositional mechanism (defuns)
# rather than TFF's to decorate "foo"
@tf.function(...)
def foo(...):
  ...

@tff.tf_computation(...)
def bar(...):
  # here relying on TensorFlow to embed "foo" as a component of "bar"
  ...foo(...)...
  1. 使用Python的组合机制(普通的未经修饰的Python函数)也是一个不错的选择,尽管它不如(1)更好,因为当TFF遍历所有TFF时,它只会使一个代码体在定义时嵌入到另一代码体中修饰的Python函数可构造要执行的计算的序列化表示形式,而不会给您带来孤立或任何其他特殊好处。

您可能仍希望使用此模式来在TFF之外或在(1)或(3)都不起作用的情况下对组件进行测试。

因此,如果(1)不起作用,以下是您应首先考虑的替代方法:

# here composing things in Python, no special TF or TFF mechanism employed
def foo(...):
  # keep in mind that in this case, "foo" can access and tamper with
  # the internal state of "bar" - you get no isolation benefits
  ...

@tff.tf_computation(...)
def bar(...):
  # here effectively just executing "foo" within "bar" at the
  # time "bar" is traced
  ...foo(...)...
  1. 不建议使用TFF的合成机制(@ tff.tf_computation),除非-如上所述-在需要它的情况下,例如TensorFlow组件需要接受数据集作为参数,或者仅将其调用时来自@ tff.federated_computation。请记住,TFF对数据集作为参数的支持仍处于试验阶段,尽管在某些情况下它可能是唯一的解决方案,但您仍然可能会遇到问题。您可以期望实现会不断发展。

不鼓励使用(尽管当前有时有必要):

# here using TFF's compositional mechanism
@tff.tf_computation(...)
def foo(...):
  # here you do get isolation benefits - "foo" is traced and
  # serialized by TFF, but you can expect that e.g., some
  # tf.data.Dataset features won't work
  ...

@tff.tf_computation(...)
def bar(...):
  # here relying on TFF to embed "foo" within "bar"
  ...foo(...)...