Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
tensorflow
GitHub Repository: tensorflow/docs-l10n
Path: blob/master/site/zh-cn/federated/tutorials/federated_select.ipynb
25118 views
Kernel: Python 3
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.

使用 tff.federated_select 向特定客户端发送不同的数据

本教程演示了如何在 TFF 中实现需要向不同客户端发送不同数据的自定义联合算法。您可能已经熟悉 tff.federated_broadcast,它用于向所有客户端发送单个服务器布局的值。本教程侧重于将基于服务器的值的不同部分发送到不同客户端的情况。这对于在不同客户端之间分配模型的各个部分以避免将整个模型发送到任何单个客户端可能十分有用。

首先,导入 tensorflowtensorflow_federated

#@test {"skip": true} !pip install --quiet --upgrade tensorflow-federated
import tensorflow as tf import tensorflow_federated as tff tff.backends.native.set_sync_local_cpp_execution_context()

根据客户数据发送不同的值

考虑这样一种情况,我们有一些服务器布局的列表,我们希望根据一些客户端布局的数据从该列表向每个客户端发送一些元素。例如,服务器上的字符串列表,以及客户端上要下载的以逗号分隔的索引列表。我们可以通过以下代码实现:

list_of_strings_type = tff.TensorType(tf.string, [None]) # We only ever send exactly two values to each client. The number of keys per # client must be a fixed number across all clients. number_of_keys_per_client = 2 keys_type = tff.TensorType(tf.int32, [number_of_keys_per_client]) get_size = tff.tf_computation(lambda x: tf.size(x)) select_fn = tff.tf_computation(lambda val, index: tf.gather(val, index)) client_data_type = tf.string # A function from our client data to the indices of the values we'd like to # select from the server. @tff.tf_computation(client_data_type) @tff.check_returns_type(keys_type) def keys_for_client(client_string): # We assume our client data is a single string consisting of exactly three # comma-separated integers indicating which values to grab from the server. split = tf.strings.split([client_string], sep=',')[0] return tf.strings.to_number([split[0], split[1]], tf.int32) @tff.tf_computation(tff.SequenceType(tf.string)) @tff.check_returns_type(tf.string) def concatenate(values): def reduce_fn(acc, item): return tf.cond(tf.math.equal(acc, ''), lambda: item, lambda: tf.strings.join([acc, item], ',')) return values.reduce('', reduce_fn) @tff.federated_computation(tff.type_at_server(list_of_strings_type), tff.type_at_clients(client_data_type)) def broadcast_based_on_client_data(list_of_strings_at_server, client_data): keys_at_clients = tff.federated_map(keys_for_client, client_data) max_key = tff.federated_map(get_size, list_of_strings_at_server) values_at_clients = tff.federated_select(keys_at_clients, max_key, list_of_strings_at_server, select_fn) value_at_clients = tff.federated_map(concatenate, values_at_clients) return value_at_clients

随后,我们可以通过为每个客户端提供服务器布局的字符串列表以及字符串数据来模拟我们的计算:

client_data = ['0,1', '1,2', '2,0'] broadcast_based_on_client_data(['a', 'b', 'c'], client_data)
[<tf.Tensor: shape=(), dtype=string, numpy=b'a,b'>, <tf.Tensor: shape=(), dtype=string, numpy=b'b,c'>, <tf.Tensor: shape=(), dtype=string, numpy=b'c,a'>]

向每个客户端发送随机化元素

另外,将服务器数据的随机部分发送到每个客户端可能很有用。我们可以通过先在每个客户端上生成一个随机密钥,然后按照与上面使用的类似的选择过程来实现此目的:

@tff.tf_computation(tf.int32) @tff.check_returns_type(tff.TensorType(tf.int32, [1])) def get_random_key(max_key): return tf.random.uniform(shape=[1], minval=0, maxval=max_key, dtype=tf.int32) list_of_strings_type = tff.TensorType(tf.string, [None]) get_size = tff.tf_computation(lambda x: tf.size(x)) select_fn = tff.tf_computation(lambda val, index: tf.gather(val, index)) @tff.tf_computation(tff.SequenceType(tf.string)) @tff.check_returns_type(tf.string) def get_last_element(sequence): return sequence.reduce('', lambda _initial_state, val: val) @tff.federated_computation(tff.type_at_server(list_of_strings_type)) def broadcast_random_element(list_of_strings_at_server): max_key_at_server = tff.federated_map(get_size, list_of_strings_at_server) max_key_at_clients = tff.federated_broadcast(max_key_at_server) key_at_clients = tff.federated_map(get_random_key, max_key_at_clients) random_string_sequence_at_clients = tff.federated_select( key_at_clients, max_key_at_server, list_of_strings_at_server, select_fn) # Even though we only passed in a single key, `federated_select` returns a # sequence for each client. We only care about the last (and only) element. random_string_at_clients = tff.federated_map(get_last_element, random_string_sequence_at_clients) return random_string_at_clients

我们的 broadcast_random_element 函数不接受任何客户端布局的数据,因此,我们必须为 TFF 模拟运行时配置要使用的默认客户端数量:

tff.backends.native.set_sync_local_cpp_execution_context(default_num_clients=3)

随后,我们可以模拟选择。我们可以更改上面的 default_num_clients 和下面的字符串列表以生成不同的结果,或者简单地重新运行计算以生成不同的随机输出。

broadcast_random_element(tf.convert_to_tensor(['foo', 'bar', 'baz']))