Coder Social home page Coder Social logo

federated's Introduction

Python PyPI DOI CII Best Practices OpenSSF Scorecard Fuzzing Status Fuzzing Status OSSRank Contributor Covenant TF Official Continuous TF Official Nightly

Documentation
Documentation

TensorFlow is an end-to-end open source platform for machine learning. It has a comprehensive, flexible ecosystem of tools, libraries, and community resources that lets researchers push the state-of-the-art in ML and developers easily build and deploy ML-powered applications.

TensorFlow was originally developed by researchers and engineers working within the Machine Intelligence team at Google Brain to conduct research in machine learning and neural networks. However, the framework is versatile enough to be used in other areas as well.

TensorFlow provides stable Python and C++ APIs, as well as a non-guaranteed backward compatible API for other languages.

Keep up-to-date with release announcements and security updates by subscribing to [email protected]. See all the mailing lists.

Install

See the TensorFlow install guide for the pip package, to enable GPU support, use a Docker container, and build from source.

To install the current release, which includes support for CUDA-enabled GPU cards (Ubuntu and Windows):

$ pip install tensorflow

Other devices (DirectX and MacOS-metal) are supported using Device plugins.

A smaller CPU-only package is also available:

$ pip install tensorflow-cpu

To update TensorFlow to the latest version, add --upgrade flag to the above commands.

Nightly binaries are available for testing using the tf-nightly and tf-nightly-cpu packages on PyPi.

Try your first TensorFlow program

$ python
>>> import tensorflow as tf
>>> tf.add(1, 2).numpy()
3
>>> hello = tf.constant('Hello, TensorFlow!')
>>> hello.numpy()
b'Hello, TensorFlow!'

For more examples, see the TensorFlow tutorials.

Contribution guidelines

If you want to contribute to TensorFlow, be sure to review the contribution guidelines. This project adheres to TensorFlow's code of conduct. By participating, you are expected to uphold this code.

We use GitHub issues for tracking requests and bugs, please see TensorFlow Forum for general questions and discussion, and please direct specific questions to Stack Overflow.

The TensorFlow project strives to abide by generally accepted best practices in open-source software development.

Patching guidelines

Follow these steps to patch a specific version of TensorFlow, for example, to apply fixes to bugs or security vulnerabilities:

  • Clone the TensorFlow repo and switch to the corresponding branch for your desired TensorFlow version, for example, branch r2.8 for version 2.8.
  • Apply (that is, cherry-pick) the desired changes and resolve any code conflicts.
  • Run TensorFlow tests and ensure they pass.
  • Build the TensorFlow pip package from source.

Continuous build status

You can find more community-supported platforms and configurations in the TensorFlow SIG Build community builds table.

Official Builds

Build Type Status Artifacts
Linux CPU Status PyPI
Linux GPU Status PyPI
Linux XLA Status TBA
macOS Status PyPI
Windows CPU Status PyPI
Windows GPU Status PyPI
Android Status Download
Raspberry Pi 0 and 1 Status Py3
Raspberry Pi 2 and 3 Status Py3
Libtensorflow MacOS CPU Status Temporarily Unavailable Nightly Binary Official GCS
Libtensorflow Linux CPU Status Temporarily Unavailable Nightly Binary Official GCS
Libtensorflow Linux GPU Status Temporarily Unavailable Nightly Binary Official GCS
Libtensorflow Windows CPU Status Temporarily Unavailable Nightly Binary Official GCS
Libtensorflow Windows GPU Status Temporarily Unavailable Nightly Binary Official GCS

Resources

Learn more about the TensorFlow community and how to contribute.

Courses

License

Apache License 2.0

federated's People

Contributors

cramertj avatar eglanz avatar galenmandrew avatar hardik-vala avatar hawkinsp avatar hbmcmahan avatar huili0140 avatar ishark avatar jkr26 avatar jvmncs avatar kairouzp avatar karan1149 avatar krzys-ostrowski avatar michaelreneer avatar nicolemitchell avatar nightldj avatar prachetit avatar sanianagpal avatar saugenst avatar slowbull avatar swegner avatar swkpku avatar tensorflow-copybara avatar tensorflower-gardener avatar wennanzhu avatar wushanshan avatar xiaoxlu avatar xiaoyux11 avatar zacharygarrett avatar zcharles8 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

federated's Issues

install and import problem

I have followed the install steps
virtualenv --python python3 "venv" source ./venv/bin/activate pip install --upgrade pip (veno) pip install --upgrade tensorflow_federated
and I have installed bazel 0.23.2
when testing python -c "import tensorflow_federated as tff; tff.federated_computation(lambda: 'Hello, World!')()" it returned bash: !': event not found

when testing the demo, it shows error import tensorflow_federated as tff
图片

Multiple inputs with keras model?

I'm trying to apply federated learning to an existing keras model that takes two inputs. When I call tff.learning.from_compiled_keras_model and include a dummy batch, I get this error: ValueError: Layer model_1 expects 2 inputs, but it received 1 input tensors. Inputs received: [<tf.Tensor 'packed:0' shape=(2, 20) dtype=int64>].

The model accepts two numpy arrays as inputs, so I defined my dummy_batch as:

x = tf.constant(np.random.randint(1,100, size=[20]))
collections.OrderedDict([('x', [x, x]), ('y', x)])

I dug around a little bit and saw that eventually, tf.convert_to_tensor_or_sparse_tensor gets called on the input list (in the __init__ for _KerasModel), and that returns a single tensor of shape (2,20), instead of two separate arrays or tensors. Is there some other way I can represent the list of inputs to avoid this issue?

Cannot use GPU to train in 0.5.0

My enviroment :
RedHat Linux 7.2
gcc 4.8.5
nvidia-driver : 410.48
cuda : 10.0
cudnn: 7.5
python2.7.5
tf-nightly-gpu==1.14.1-dev20190604
tensorflow_federated==0.5.0

When I use the example: federated_learning_for_image_classification.ipynb.
I change the model
model = tf.keras.models.Sequential([ tf.keras.layers.Dense( 10, activation=tf.nn.softmax, kernel_initializer='zeros', input_shape=(784,))])
to like this below:
model = tf.keras.models.Sequential([ tf.keras.layers.Reshape(target_shape=[28, 28, 1], input_shape=(28 * 28,)), tf.keras.layers.Conv2D( 32, 5, padding='same', activation=tf.nn.relu), tf.keras.layers.MaxPooling2D((2, 2), (2, 2), padding='same'), tf.keras.layers.Conv2D( 64, 5, padding='same', activation=tf.nn.relu), tf.keras.layers.MaxPooling2D((2, 2), (2, 2), padding='same'), tf.keras.layers.Flatten(), tf.keras.layers.Dense( 10, activation=tf.nn.softmax, kernel_initializer='zeros') ])
It show
MaxPoolingOp only support NHWC on device type cpu.
When I comment the all MaxPooling2D layer,
it also show the similar but more confuse problem:
Conv2DCustomBackprofFilterOp only supports NHWC.

I only change the model.
And I run this code in tf-nightly==1.14.1-dev20190604 (cpu versoin) it is fine.

Can anyone help?
Thanks

machine learning

Hello, there exists an example of a machine learning model? How do I use tff to deploy my own machine learning model? Thank you!

tff tutorial notebooks are broken

For text generation, it would stuck on

#@test {"output": "ignore"}
iterative_process = tff.learning.build_federated_averaging_process(model_fn)

with error message

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-15-0fdb188570d0> in <module>()
----> 1 iterative_process = tff.learning.build_federated_averaging_process(model_fn)

17 frames
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/util/deprecation_wrapper.py in __getattr__(self, name)
    102     if name.startswith('_dw_'):
    103       raise AttributeError('Accessing local variables before they are created.')
--> 104     attr = getattr(self._dw_wrapped_module, name)
    105     if (self._dw_warning_count < _PER_MODULE_WARNING_LIMIT and
    106         name not in self._dw_deprecated_printed):

AttributeError: module 'tensorflow._api.v1.data.experimental' has no attribute 'NestedStructure'

However on my machine the error is different, I can build the averaging process, but would stuck on the next step:

state = fed_avg.initialize()
state, metrics = fed_avg.next(state, [example_dataset.take(1)])
print(metrics)

with error message

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-aa5f31726a7a> in <module>
      1 state = fed_avg.initialize()
----> 2 state, metrics = fed_avg.next(state, [example_dataset.take(1)])
      3 print(metrics)

~\Anaconda3\envs\tff\lib\site-packages\tensorflow_federated\python\core\impl\function_utils.py in __call__(self, *args, **kwargs)
    628   def __call__(self, *args, **kwargs):
    629     context = self._context_stack.current
--> 630     arg = pack_args(self._type_signature.parameter, args, kwargs, context)
    631     return context.invoke(self, arg)
    632 

~\Anaconda3\envs\tff\lib\site-packages\tensorflow_federated\python\core\impl\function_utils.py in pack_args(parameter_type, args, kwargs, context)
    385       else:
    386         arg = pack_args_into_anonymous_tuple(args, kwargs, parameter_type,
--> 387                                              context)
    388       return context.ingest(arg, parameter_type)
    389 

~\Anaconda3\envs\tff\lib\site-packages\tensorflow_federated\python\core\impl\function_utils.py in pack_args_into_anonymous_tuple(args, kwargs, type_spec, context)
    307           else:
    308             arg_value = args[index]
--> 309             result_elements.append((name, context.ingest(arg_value, elem_type)))
    310             positions_used.add(index)
    311         elif name is not None and name in kwargs:

~\Anaconda3\envs\tff\lib\site-packages\tensorflow_federated\python\core\impl\reference_executor.py in ingest(self, arg, type_spec)
    666       return fn
    667 
--> 668     return to_representation_for_type(arg, type_spec, _handle_callable)
    669 
    670   def invoke(self, fn, arg):

~\Anaconda3\envs\tff\lib\site-packages\tensorflow_federated\python\core\impl\reference_executor.py in to_representation_for_type(value, type_spec, callable_handler)
    240       return [
    241           to_representation_for_type(v, type_spec.member, callable_handler)
--> 242           for v in value
    243       ]
    244   else:

~\Anaconda3\envs\tff\lib\site-packages\tensorflow_federated\python\core\impl\reference_executor.py in <listcomp>(.0)
    240       return [
    241           to_representation_for_type(v, type_spec.member, callable_handler)
--> 242           for v in value
    243       ]
    244   else:

~\Anaconda3\envs\tff\lib\site-packages\tensorflow_federated\python\core\impl\reference_executor.py in to_representation_for_type(value, type_spec, callable_handler)
    199         return [
    200             to_representation_for_type(v, type_spec.element, callable_handler)
--> 201             for v in value
    202         ]
    203       else:

~\Anaconda3\envs\tff\lib\site-packages\tensorflow_federated\python\core\impl\reference_executor.py in <listcomp>(.0)
    199         return [
    200             to_representation_for_type(v, type_spec.element, callable_handler)
--> 201             for v in value
    202         ]
    203       else:

~\Anaconda3\envs\tff\lib\site-packages\tensorflow_federated\python\core\impl\reference_executor.py in to_representation_for_type(value, type_spec, callable_handler)
    191                 value_elem_name, type_elem_name, index, value, type_spec))
    192       converted_value_elem = to_representation_for_type(value_elem, type_elem,
--> 193                                                         callable_handler)
    194       result_elements.append((type_elem_name, converted_value_elem))
    195     return anonymous_tuple.AnonymousTuple(result_elements)

~\Anaconda3\envs\tff\lib\site-packages\tensorflow_federated\python\core\impl\reference_executor.py in to_representation_for_type(value, type_spec, callable_handler)
    163       raise TypeError(
    164           'The tensor type {} of the value representation does not match '
--> 165           'the type spec {}.'.format(str(inferred_type_spec), str(type_spec)))
    166     return value
    167   elif isinstance(type_spec, computation_types.NamedTupleType):

TypeError: The tensor type int64[8,100] of the value representation does not match the type spec int32[?,100].

Similarly, the notebook for image classification doesn't work as well.

Why the evaluation on test using the sample_clients from training in the EMNIST tutorial?

I went through the EMNIST tutorial https://www.tensorflow.org/federated/tutorials/federated_learning_for_image_classification
, but found the problem in the evaluation section:

federated_test_data = make_federated_data(emnist_test, sample_clients)
len(federated_test_data), federated_test_data[0]

The federated_test_data is generated from sample_clients, while the sample_clients comes from the training set

#@test {"output": "ignore"}
NUM_CLIENTS = 3
sample_clients = emnist_train.client_ids[0:NUM_CLIENTS]
federated_train_data = make_federated_data(emnist_train, sample_clients)
len(federated_train_data), federated_train_data[0]

Why not take it as

sample_clients_test = emnist_test.client_ids[0:NUM_CLIENTS]
federated_test_data = make_federated_data(emnist_test, sample_clients_test)
evaluation(state.model, federated_test_data)

Is that an error or can someone explain it?

Tensor is not an element of this graph

I've tried to reproduce a tutorial "Federated Learning for Image Classification" in Colab [1] and encountered a ValueError during execution

iterative_process = tff.learning.build_federated_averaging_process(model_fn)

The error is following:

 ---------------------------------------------------------------------------
 ValueError                                Traceback (most recent call last)
 /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    1091             subfeed_t = self.graph.as_graph_element(
 -> 1092                 subfeed, allow_tensor=True, allow_operation=False)
    1093           except Exception as e:

 /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py in as_graph_element(self, obj, allow_tensor, allow_operation)
    3477     with self._lock:
 -> 3478       return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
    3479 

 /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py in _as_graph_element_locked(self, obj, allow_tensor, allow_operation)
    3556       if obj.graph is not self:
 -> 3557         raise ValueError("Tensor %s is not an element of this graph." % obj)
    3558       return obj

 ValueError: Tensor Tensor("Placeholder:0", shape=(), dtype=float32) is not an element of this graph.

How it can be solved?

[1] https://colab.research.google.com/github/tensorflow/federated/blob/master/docs/tutorials/federated_learning_for_image_classification.ipynb

Follow up on #258 TFF with BatchNormalization

Hello
I followed the discussion on #258 about keras models with batch_normalization, this is the relevant part of the code:

for round_num in range(2, 70): 
    FLstate, FLoutputs = trainer_Itr_Process.next(FLstate, federated_train_data)   
    FLlosses_arr.append(FLoutputs.loss)
    tff_weights= tff.learning.keras_weights_from_tff_weights(FLstate.model)
    tff_weights.assign_weights_to(tff_weights, Local_model_Fed)

I appreciate the help with the following error:

Traceback (most recent call last):
  File "C:\Users\ezalaab\.p2\pool\plugins\org.python.pydev.core_7.1.0.201902031515\pysrc\pydevd.py", line 2225, in <module>
    main()
  File "C:\Users\ezalaab\.p2\pool\plugins\org.python.pydev.core_7.1.0.201902031515\pysrc\pydevd.py", line 2218, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "C:\Users\ezalaab\.p2\pool\plugins\org.python.pydev.core_7.1.0.201902031515\pysrc\pydevd.py", line 1560, in run
    return self._exec(is_module, entry_point_fn, module_name, file, globals, locals)
  File "C:\Users\ezalaab\.p2\pool\plugins\org.python.pydev.core_7.1.0.201902031515\pysrc\pydevd.py", line 1567, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:\Users\ezalaab\.p2\pool\plugins\org.python.pydev.core_7.1.0.201902031515\pysrc\_pydev_imps\_pydev_execfile.py", line 25, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:\Users\ezalaab\Documents\eclipse-workspace\MANA-FederatedLearning\location-based-federated-learning\Test\FederatedLearningTFv3.py", line 299, in <module>
    tff_weights.assign_weights_to(tff_weights, Local_model_Fed)
AttributeError: 'list' object has no attribute 'assign_weights_to

Error tf.keras.losses

Hello, i am trying with the tutorial of image classification when I met the error which said "keras.losses' has no attribute 'SparseCategoricalCrossentropy'". How to fix it? Is that a problem of version of my tensorflow?
Another question is that how many kinds of loss functions does tff support?
Thank you in advance!

Results cannot improve by rounding (.next): Federated TF

Hello

I'm trying to compare federated learning TF with keras fitting, as we see below. However, the results of TFF does not improve by rounding. Also, when I set weight a local model based on the TFF model, I get worse results than normally training the model on keras. The Loss results are mentioned after the code.

Thanks for the help.

Regards

Code:

tf.compat.v1.enable_v2_behavior()

TobeRemoved_Array = ['feature1','feature2','feature3','feature4','feature5','feature6','feature7', 'is_training']

train_perc = 0.8
Norm_Input = True
Norm_Output = False
Input_str = ['feature1', 'feature2']
if Norm_Output:
Output_str = ['feature3']
else:
Output_str = ['feature4']

Final_Tag = 'Tag3' # here just decide which tagging method do you want to use
Num_Clients = 10 # cannot be less than one
Num_Cons_Sample_Client = 5 # cannot be less than one

Load simulation data.

##############################################
dir_name = 'pickle-data/'
file_name = 'logs_april_2019.pickle'
files = os.listdir('pickle-data/')
dataframe = Import_Pickle.Import_v1(dir_name,file_name,False) # choose False to use 2019 data

Just to reduce the processing

ave = dataframe.core.min() + 1000000000
df2 = dataframe[dataframe.core < ave]
df = Import_Pickle.PreProcessing_v2019(df2,Norm_Input)
train_df,test_df,X_traindf,X_testdf,Y_traindf,Y_testdf,XY_traindf,XY_testdf = Import_Pickle.Splitting_Train_Test(df,train_perc,Norm_Output,TobeRemoved_Array)
########## splitting for clients ############
def Tag_per_day(train_df_loc,TagNum):
train_df_loc['log2'] = train_df_loc['log'].apply(lambda x: x.replace("_",""))
tag_Index = train_df_loc.log2.apply(lambda x: x.index("201"))
tag_Index2 = tag_Index.values[1]
tag_date =train_df_loc.log2.apply(lambda x: x[tag_Index2:tag_Index2+8])
train_df_loc.loc[:,'Tag'+str(TagNum)] = pd.Series(tag_date.to_list(),index=train_df.index) # to be fixed
return train_df_loc

Introduce time as input

X_traindf['feature1'] = train_df['feature1']

introduce first tag per day

TagNum=1
train_df = Tag_per_day(train_df,TagNum)
#examples on groupby
Unq_tag1_grps = list(train_df.groupby(train_df.Tag1).groups.keys())
train_df.groupby(train_df.Tag1).first()
train_df.groupby(train_df.Tag1)['feature1'].count()
X_traindf['Tag'+str(TagNum)] = train_df['Tag'+str(TagNum)]
#############################

introduce epoch as tag

#############################
TagNum=2
train_df['Tag'+str(TagNum)] = train_df.epoch
X_traindf['Tag'+str(TagNum)] = train_df['Tag'+str(TagNum)]
#############################

introduce core as tag

#############################
TagNum=3
train_df['Tag'+str(TagNum)] = train_df.core
X_traindf['Tag'+str(TagNum)] = train_df['Tag'+str(TagNum)]
#############################

introduce day as tag per client

#############################
TagNum = 4
RepNum = np.ceil(train_df.shape[0]/(Num_Cons_Sample_Client*Num_Clients))
Part_Tag_Array=[]
for i in np.arange(Num_Clients):
Part_Tag_Tmp = list(map(lambda _: i+1,range(Num_Cons_Sample_Client)))
Part_Tag_Array.extend(Part_Tag_Tmp)

Full_Tag_Array2 = Part_Tag_Array * int(RepNum)
extra_tags = np.abs(len(Full_Tag_Array2) - train_df.shape[0])
Full_Tag_Array = Full_Tag_Array2[:-extra_tags]

train_df.loc[:,'Tag'+str(TagNum)] = pd.Series(Full_Tag_Array,index=train_df.index)
X_traindf.loc[:,'Tag'+str(TagNum)] = train_df['Tag'+str(TagNum)]
#############################

END day as tag per client

#############################
######### Introduce gpsTime and Tag to the input
Input_str.extend(['feature1',Final_Tag])

Adding StandardSalarization:

scaler = StandardScaler()
removed_column = Input_str.pop()
X_train_ScaledTmp = scaler.fit_transform(X_traindf[Input_str],Y_traindf[Output_str])

Adding Int tag per client without scalarization

X_train_Scaled = np.c_[X_train_ScaledTmp, train_df[removed_column].values.reshape(train_df.shape[0],1)]

All In/Out data Numpy

Act_Inputs_Int_Tag = X_train_Scaled
Act_Outputs_Int = Y_traindf[Output_str].values

Remove Tags

Act_Inputs_Int = np.delete(Act_Inputs_Int_Tag,-1,axis=1)

prepare In/Out per Client

All_Act_Inputs_Int_Tag = [Act_Inputs_Int_Tag[np.where(Act_Inputs_Int_Tag[:,-1]== x)] for x in np.arange(1,Num_Clients+1)]
All_Act_Outputs_Int = [Act_Outputs_Int[np.where(Act_Inputs_Int_Tag[:,-1]== x)] for x in np.arange(1,Num_Clients+1)]

Remove Tags

All_Act_Inputs_Int = [np.delete(All_Act_Inputs_Int_Tag[x],-1,axis=1) for x in np.arange(0,Num_Clients) ]

a need conversion to float32

Act_Inputs = np.float32(Act_Inputs_Int)
Act_Outputs = np.float32(Act_Outputs_Int)

convert dataset to client based dataset

All_Act_Inputs = [np.float32(All_Act_Inputs_Int[x]) for x in np.arange(0,Num_Clients)]
All_Act_Outputs = [np.float32(All_Act_Outputs_Int[x]) for x in np.arange(0,Num_Clients)]

convert to OrderedDict

new_batch = collections.OrderedDict([('In', Act_Inputs),('Out', Act_Outputs)])
All_new_batch = [collections.OrderedDict([('In', All_Act_Inputs[x]),('Out', All_Act_Outputs[x])]) for x in np.arange(0,Num_Clients)]

Convert to tensor

dataset_input = tf.data.Dataset.from_tensor_slices(new_batch)#,,maxval=100, dtype=tf.float32)

All_new_batch has different item per In / Out

All_dataset_input = [tf.data.Dataset.from_tensor_slices(All_new_batch[x]) for x in np.arange(0,Num_Clients)]

Select among the datasets

Used_dataset= dataset_input
All_Used_dataset= All_dataset_input

#with eager_mode():
learning_rate = 1
Val_Train_Split = 0.8
SNN_epoch = 50
SNN_batch_size = 1100
shuffle_buffer = 200

def preprocess(new_dataset):
#return Used_dataset.repeat(2).batch(2)
def map_fn(elem):
return collections.OrderedDict([('x', tf.reshape(elem['In'], [-1])),('y', tf.reshape(elem['Out'],[1]))])

DS2= new_dataset.map(map_fn)
return DS2.repeat(SNN_epoch).batch(SNN_batch_size)

train_data = [preprocess(Used_dataset)]

#######changes###############33
def make_federated_data(client_data, client_ids):
return [preprocess(client_data[x]) for x in client_ids]

federated_train_data = make_federated_data(All_Used_dataset, np.arange(0,Num_Clients))

sample_batch = tf.contrib.framework.nest.map_structure(lambda x: x.numpy(), next(iter(train_data[0])))

########## END Changes ############

def create_SK_model():
modelF = tf.keras.Sequential([tf.keras.layers.Flatten(input_shape=(Act_Inputs.shape[1],)),
tf.keras.layers.Dense(10, activation=tf.nn.relu, kernel_initializer='zeros'),
tf.keras.layers.Dense(100, activation=tf.nn.relu, kernel_initializer='zeros'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(100, activation=tf.nn.relu, kernel_initializer='zeros'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(1, activation=tf.nn.relu, kernel_initializer='zeros'),
])
return modelF

def loss_fn(y_true, y_pred):
return tf.reduce_mean(tf.keras.losses.MSE(y_true, y_pred))

def model_fn():
return tff.learning.from_keras_model(create_SK_model(),
sample_batch, loss=loss_fn,
optimizer=gradient_descent.SGD(0.1))

YTrain = Act_Outputs #np.random.rand(50,1)
XTrain = Act_Inputs #np.random.rand(50,100)

locally compile the model

Local_model = create_SK_model()
Local_model.compile(loss=loss_fn,optimizer=gradient_descent.SGD(learning_rate))

training/fitting with TF federated learning

trainer_Itr_Process = tff.learning.build_federated_averaging_process(model_fn,server_optimizer_fn=(lambda : gradient_descent.SGD(learning_rate=1.0)),client_weight_fn=None)
FLstate = trainer_Itr_Process.initialize()
FLlosses = []

Track loss of different ...... of federated iteration

for round_num in range(2, 5):
"""
The second of the pair of federated computations, next, represents a single round of Federated Averaging, which consists of pushing the server state (including the model parameters) to the clients, on-device training on their local data, collecting and averaging model updates, and producing a new updated model at the server.
"""
FLstate, FLoutputs = trainer_Itr_Process.next(FLstate, federated_train_data)
print('round {:2d}, metrics={}'.format(round_num, FLoutputs.loss))
# Track the loss.
FLlosses.append(FLoutputs.loss)

fitting without federated learning

trained_local_Model = Local_model.fit(XTrain,YTrain, validation_split=Val_Train_Split, epochs=SNN_epoch, batch_size=SNN_batch_size) #tbuc

Loss of local model

local_Loss = trained_local_Model.history['loss'] # tbuc
print("Local Model Loss: "+str(local_Loss))

Copy local model for comparison purposes

Local_model_Fed = Local_model

Setting federated weights on copied Object of local model

Local_model_Fed.set_weights(tff.learning.keras_weights_from_tff_weights(FLstate.model))

Evaluate loss of the copied federated weights on local model

Fed_predicted = Local_model_Fed.predict(XTrain)
Fed_eval = Local_model_Fed.evaluate(XTrain,YTrain)

print("Local Model with Federated Weights Loss: "+str(Fed_eval ))
print("New: " + str(Local_model_Fed.loss))
print('End')

Output:

round 2, metrics=6838.99658203125
round 3, metrics=6838.99658203125
round 4, metrics=6838.99658203125
round 5, metrics=6838.99658203125
round 6, metrics=6838.99658203125
Train on 733 samples, validate on 2936 samples
Epoch 1/50

733/733 [==============================] - 0s 14us/sample - loss: 6449.8022 - val_loss: 6936.1622
Epoch 4/50
.........................................................
733/733 [==============================] - 0s 18us/sample - loss: 6449.8022 - val_loss: 6936.1622

Local Model Loss: [6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375, 6449.80224609375]

32/3669 [..............................] - ETA: 0s - loss: 10104.2188
1632/3669 [============>.................] - ETA: 0s - loss: 6897.5380
3232/3669 [=========================>....] - ETA: 0s - loss: 6860.1061
3669/3669 [==============================] - 0s 31us/sample - loss: 6838.9962
Local Model with Federated Weights Loss: 6838.996183714057

About the server

Hello, I would like to ask, there is no data training on the server side, but the server will merge the models of each client and update based on FedAvg algorithm, then the model I got is the final server model? Moreover, how do I get the client model?

Federated in Tensorflow.js

Will this api be exposed in Tensorflow.js?
So that you can join in the federation from a browser tab.

Error in pip installation in venv: No matching distribution found

When following the install from package instructions, I receive an error when attempting pip installation: Could not find a version that satisfies the requirement tensorflow_federated (from versions: ) No matching distribution found for tensorflow_federated

Steps to reproduce:

$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
$ export PATH="/usr/local/bin:/usr/local/sbin:$PATH"
$ brew update
$ brew install python  # Python 3
$ sudo pip3 install --upgrade virtualenv  # system-wide install
$ virtualenv --python python3 "venv"
$ source "venv/bin/activate"
(venv) $ pip install --upgrade pip
(venv) $ pip install tensorflow_federated
Collecting tensorflow_federated
*Could not find a version that satisfies the requirement tensorflow_federated (from versions: )
No matching distribution found for tensorflow_federated*

System info:

pip 10.0.1
Homebrew 2.0.1
Python 3.6.7
macOS High Sierra 10.13.6

Using GPU produces error after upgrading to 0.4.0

I updated TFF to 0.4.0 yesterday and found that the image classification tutorial cannot be run correctly now (which worked in previous TFF versions). After executing

#@test {"timeout": 600, "output": "ignore"}
state, metrics = iterative_process.next(state, federated_train_data)
print('round 1, metrics={}'.format(metrics))

The following error message occurs. I believe this problem is also partly mentioned here. Plus, I am interested in knowing of optimizing GPU usage for TFF possibly by looping on the clients in parallel (as the previous closed issue). Or is there any advice on speeding up the federated training? Now it takes really long time when having a large neural network. Thank you!


InvalidArgumentError Traceback (most recent call last)
~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
1333 try:
-> 1334 return fn(*args)
1335 except errors.OpError as e:

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run_fn(feed_dict, fetch_list, target_list, options, run_metadata)
1318 return self._call_tf_sessionrun(
-> 1319 options, feed_dict, fetch_list, target_list, run_metadata)
1320

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/client/session.py in _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, run_metadata)
1406 self._session, options, feed_dict, fetch_list, target_list,
-> 1407 run_metadata)
1408

InvalidArgumentError: Could not colocate node with its resource and reference inputs; devices /job:localhost/replica:0/task:0/device:CPU:0 and /job:localhost/replica:0/task:0/device:GPU:0 are not compatible.
[[{{node ReduceDataset}}]]
[[{{node subcomputation/StatefulPartitionedCall_1}}]]
[[{{node subcomputation/StatefulPartitionedCall_1}}]]

During handling of the above exception, another exception occurred:

InvalidArgumentError Traceback (most recent call last)
in ()
1 #@test {"timeout": 600, "output": "ignore"}
----> 2 state, metrics = iterative_process.next(state, federated_train_data)
3 print('round 1, metrics={}'.format(metrics))

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/function_utils.py in call(self, *args, **kwargs)
598 context = self._context_stack.current
599 arg = pack_args(self._type_signature.parameter, args, kwargs, context)
--> 600 return context.invoke(self, arg)
601
602

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in invoke(self, fn, arg)
698 else:
699 computed_arg = None
--> 700 result = computed_comp.value(computed_arg)
701 py_typecheck.check_type(result, ComputedValue)
702 type_utils.check_assignable_from(comp.type_signature.result,

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in (x)
841 return ComputationContext(context, {comp.parameter_name: arg})
842
--> 843 return ComputedValue(lambda x: self._compute(comp.result, _wrap(x)),
844 comp.type_signature)
845

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute(self, comp, context)
744 return self._compute_call(comp, context)
745 elif isinstance(comp, computation_building_blocks.Tuple):
--> 746 return self._compute_tuple(comp, context)
747 elif isinstance(comp, computation_building_blocks.Reference):
748 return self._compute_reference(comp, context)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute_tuple(self, comp, context)
800 result_type_elements = []
801 for k, v in anonymous_tuple.to_elements(comp):
--> 802 computed_v = self._compute(v, context)
803 type_utils.check_assignable_from(v.type_signature,
804 computed_v.type_signature)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute(self, comp, context)
742 return self._compute_compiled(comp, context)
743 elif isinstance(comp, computation_building_blocks.Call):
--> 744 return self._compute_call(comp, context)
745 elif isinstance(comp, computation_building_blocks.Tuple):
746 return self._compute_tuple(comp, context)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute_call(self, comp, context)
782 computation_types.FunctionType)
783 if comp.argument is not None:
--> 784 computed_arg = self._compute(comp.argument, context)
785 type_utils.check_assignable_from(computed_fn.type_signature.parameter,
786 computed_arg.type_signature)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute(self, comp, context)
744 return self._compute_call(comp, context)
745 elif isinstance(comp, computation_building_blocks.Tuple):
--> 746 return self._compute_tuple(comp, context)
747 elif isinstance(comp, computation_building_blocks.Reference):
748 return self._compute_reference(comp, context)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute_tuple(self, comp, context)
800 result_type_elements = []
801 for k, v in anonymous_tuple.to_elements(comp):
--> 802 computed_v = self._compute(v, context)
803 type_utils.check_assignable_from(v.type_signature,
804 computed_v.type_signature)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute(self, comp, context)
742 return self._compute_compiled(comp, context)
743 elif isinstance(comp, computation_building_blocks.Call):
--> 744 return self._compute_call(comp, context)
745 elif isinstance(comp, computation_building_blocks.Tuple):
746 return self._compute_tuple(comp, context)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute_call(self, comp, context)
782 computation_types.FunctionType)
783 if comp.argument is not None:
--> 784 computed_arg = self._compute(comp.argument, context)
785 type_utils.check_assignable_from(computed_fn.type_signature.parameter,
786 computed_arg.type_signature)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute(self, comp, context)
744 return self._compute_call(comp, context)
745 elif isinstance(comp, computation_building_blocks.Tuple):
--> 746 return self._compute_tuple(comp, context)
747 elif isinstance(comp, computation_building_blocks.Reference):
748 return self._compute_reference(comp, context)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute_tuple(self, comp, context)
800 result_type_elements = []
801 for k, v in anonymous_tuple.to_elements(comp):
--> 802 computed_v = self._compute(v, context)
803 type_utils.check_assignable_from(v.type_signature,
804 computed_v.type_signature)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute(self, comp, context)
742 return self._compute_compiled(comp, context)
743 elif isinstance(comp, computation_building_blocks.Call):
--> 744 return self._compute_call(comp, context)
745 elif isinstance(comp, computation_building_blocks.Tuple):
746 return self._compute_tuple(comp, context)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute_call(self, comp, context)
782 computation_types.FunctionType)
783 if comp.argument is not None:
--> 784 computed_arg = self._compute(comp.argument, context)
785 type_utils.check_assignable_from(computed_fn.type_signature.parameter,
786 computed_arg.type_signature)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute(self, comp, context)
744 return self._compute_call(comp, context)
745 elif isinstance(comp, computation_building_blocks.Tuple):
--> 746 return self._compute_tuple(comp, context)
747 elif isinstance(comp, computation_building_blocks.Reference):
748 return self._compute_reference(comp, context)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute_tuple(self, comp, context)
800 result_type_elements = []
801 for k, v in anonymous_tuple.to_elements(comp):
--> 802 computed_v = self._compute(v, context)
803 type_utils.check_assignable_from(v.type_signature,
804 computed_v.type_signature)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute(self, comp, context)
742 return self._compute_compiled(comp, context)
743 elif isinstance(comp, computation_building_blocks.Call):
--> 744 return self._compute_call(comp, context)
745 elif isinstance(comp, computation_building_blocks.Tuple):
746 return self._compute_tuple(comp, context)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute_call(self, comp, context)
782 computation_types.FunctionType)
783 if comp.argument is not None:
--> 784 computed_arg = self._compute(comp.argument, context)
785 type_utils.check_assignable_from(computed_fn.type_signature.parameter,
786 computed_arg.type_signature)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute(self, comp, context)
744 return self._compute_call(comp, context)
745 elif isinstance(comp, computation_building_blocks.Tuple):
--> 746 return self._compute_tuple(comp, context)
747 elif isinstance(comp, computation_building_blocks.Reference):
748 return self._compute_reference(comp, context)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute_tuple(self, comp, context)
800 result_type_elements = []
801 for k, v in anonymous_tuple.to_elements(comp):
--> 802 computed_v = self._compute(v, context)
803 type_utils.check_assignable_from(v.type_signature,
804 computed_v.type_signature)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute(self, comp, context)
742 return self._compute_compiled(comp, context)
743 elif isinstance(comp, computation_building_blocks.Call):
--> 744 return self._compute_call(comp, context)
745 elif isinstance(comp, computation_building_blocks.Tuple):
746 return self._compute_tuple(comp, context)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute_call(self, comp, context)
782 computation_types.FunctionType)
783 if comp.argument is not None:
--> 784 computed_arg = self._compute(comp.argument, context)
785 type_utils.check_assignable_from(computed_fn.type_signature.parameter,
786 computed_arg.type_signature)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute(self, comp, context)
744 return self._compute_call(comp, context)
745 elif isinstance(comp, computation_building_blocks.Tuple):
--> 746 return self._compute_tuple(comp, context)
747 elif isinstance(comp, computation_building_blocks.Reference):
748 return self._compute_reference(comp, context)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute_tuple(self, comp, context)
800 result_type_elements = []
801 for k, v in anonymous_tuple.to_elements(comp):
--> 802 computed_v = self._compute(v, context)
803 type_utils.check_assignable_from(v.type_signature,
804 computed_v.type_signature)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute(self, comp, context)
742 return self._compute_compiled(comp, context)
743 elif isinstance(comp, computation_building_blocks.Call):
--> 744 return self._compute_call(comp, context)
745 elif isinstance(comp, computation_building_blocks.Tuple):
746 return self._compute_tuple(comp, context)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute_call(self, comp, context)
782 computation_types.FunctionType)
783 if comp.argument is not None:
--> 784 computed_arg = self._compute(comp.argument, context)
785 type_utils.check_assignable_from(computed_fn.type_signature.parameter,
786 computed_arg.type_signature)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute(self, comp, context)
744 return self._compute_call(comp, context)
745 elif isinstance(comp, computation_building_blocks.Tuple):
--> 746 return self._compute_tuple(comp, context)
747 elif isinstance(comp, computation_building_blocks.Reference):
748 return self._compute_reference(comp, context)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute_tuple(self, comp, context)
800 result_type_elements = []
801 for k, v in anonymous_tuple.to_elements(comp):
--> 802 computed_v = self._compute(v, context)
803 type_utils.check_assignable_from(v.type_signature,
804 computed_v.type_signature)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute(self, comp, context)
742 return self._compute_compiled(comp, context)
743 elif isinstance(comp, computation_building_blocks.Call):
--> 744 return self._compute_call(comp, context)
745 elif isinstance(comp, computation_building_blocks.Tuple):
746 return self._compute_tuple(comp, context)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute_call(self, comp, context)
782 computation_types.FunctionType)
783 if comp.argument is not None:
--> 784 computed_arg = self._compute(comp.argument, context)
785 type_utils.check_assignable_from(computed_fn.type_signature.parameter,
786 computed_arg.type_signature)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute(self, comp, context)
744 return self._compute_call(comp, context)
745 elif isinstance(comp, computation_building_blocks.Tuple):
--> 746 return self._compute_tuple(comp, context)
747 elif isinstance(comp, computation_building_blocks.Reference):
748 return self._compute_reference(comp, context)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute_tuple(self, comp, context)
800 result_type_elements = []
801 for k, v in anonymous_tuple.to_elements(comp):
--> 802 computed_v = self._compute(v, context)
803 type_utils.check_assignable_from(v.type_signature,
804 computed_v.type_signature)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute(self, comp, context)
742 return self._compute_compiled(comp, context)
743 elif isinstance(comp, computation_building_blocks.Call):
--> 744 return self._compute_call(comp, context)
745 elif isinstance(comp, computation_building_blocks.Tuple):
746 return self._compute_tuple(comp, context)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _compute_call(self, comp, context)
789 else:
790 computed_arg = None
--> 791 result = computed_fn.value(computed_arg)
792 py_typecheck.check_type(result, ComputedValue)
793 type_utils.check_assignable_from(computed_fn.type_signature.result,

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in (x)
869 arg_type = comp.type_signature.parameter
870 return ComputedValue(
--> 871 lambda x: my_method(fit_argument(x, arg_type, context)),
872 comp.type_signature)
873 else:

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in _federated_map(self, arg)
912 fn = arg.value[0]
913 result_val = [
--> 914 fn(ComputedValue(x, mapping_type.parameter)).value for x in arg.value[1]
915 ]
916 result_type = computation_types.FederatedType(mapping_type.result,

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in (.0)
912 fn = arg.value[0]
913 result_val = [
--> 914 fn(ComputedValue(x, mapping_type.parameter)).value for x in arg.value[1]
915 ]
916 result_type = computation_types.FederatedType(mapping_type.result,

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in (x)
773 'but found '{}' instead.'.format(computation_oneof))
774 else:
--> 775 return ComputedValue(lambda x: run_tensorflow(comp, x),
776 comp.type_signature)
777

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/reference_executor.py in run_tensorflow(comp, arg)
342 if init_op:
343 sess.run(init_op)
--> 344 result_val = graph_utils.fetch_value_in_session(sess, result)
345 return capture_computed_value_from_graph(result_val,
346 comp.type_signature.result)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/graph_utils.py in fetch_value_in_session(sess, value)
759 if not tf.contrib.framework.is_tensor(v):
760 raise ValueError('Unsupported value type {}.'.format(str(v)))
--> 761 flattened_results = sess.run(flattened_value)
762
763 def _to_unicode(v):

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
927 try:
928 result = self._run(None, fetches, feed_dict, options_ptr,
--> 929 run_metadata_ptr)
930 if run_metadata:
931 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
1150 if final_fetches or final_targets or (handle and feed_dict_tensor):
1151 results = self._do_run(handle, final_targets, final_fetches,
-> 1152 feed_dict_tensor, options, run_metadata)
1153 else:
1154 results = []

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
1326 if handle is None:
1327 return self._do_call(_run_fn, feeds, fetches, targets, options,
-> 1328 run_metadata)
1329 else:
1330 return self._do_call(_prun_fn, handle, feeds, fetches)

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
1346 pass
1347 message = error_interpolation.interpolate(message, self._graph)
-> 1348 raise type(e)(node_def, op, message)
1349
1350 def _extend_graph(self):

InvalidArgumentError: Could not colocate node with its resource and reference inputs; devices /job:localhost/replica:0/task:0/device:CPU:0 and /job:localhost/replica:0/task:0/device:GPU:0 are not compatible.
[[{{node ReduceDataset}}]]
[[node subcomputation/StatefulPartitionedCall_1 (defined at /home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/tensorflow_deserialization.py:122) ]]
[[node subcomputation/StatefulPartitionedCall_1 (defined at /home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/tensorflow_deserialization.py:122) ]]

ImportError: cannot import name 'computation_pb2'

When running the code ''tensorflow_federated/python/examples/mnist/models_test.py'', I got an error

File "/home/wzy/Desktop/github_project/federated-master/tensorflow_federated/python/core/impl/computation_impl.py", line 20, in
from tensorflow_federated.proto.v0 import computation_pb2 as pb
ImportError: cannot import name 'computation_pb2'

Then I viewed the folder tensorflow_federated/proto/v0, I find there are no file named computation_pb2, could you please tell me what should I do? @michaelreneer @jkr26
Thank you!

The performance of the algorithm in tff is much lower

Hello,
When I use the logistic regression algorithm to perform the two classification task on tff, the performance of the training is reduced compared to using only the logistic regression algorithm. What is the reason? I just divided a large data set into several small data sets. They have the same feature. Below is my result. Can you tell me why?
in tff: accuracy=0.55
only logisitic regression: accuracy=0.71

AttributeError: module 'tensorflow_federated.python' has no attribute 'federated_mean'

When i execute image classification example(Customizing the model implementation) on PyCharm in the link below:
https://github.com/tensorflow/federated/blob/master/docs/tutorials/federated_learning_for_image_classification.ipynb

wrong:
Traceback (most recent call last):
File "/data/PycharmProjects/federated_learning/test.py", line 120, in
MnistTrainableModel)
File "/home/BH/fyn123456/.conda/envs/py36/lib/python3.6/site-packages/tensorflow_federated/python/learning/federated_averaging.py", line 149, in build_federated_averaging_process
model_fn, client_fed_avg, server_optimizer_fn)
File "/home/BH/fyn123456/.conda/envs/py36/lib/python3.6/site-packages/tensorflow_federated/python/learning/framework/optimizer_utils.py", line 303, in build_model_delta_optimizer_process
federated_dataset_type)
File "/home/BH/fyn123456/.conda/envs/py36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/computation_wrapper.py", line 408, in
return lambda fn: _wrap(fn, arg_type, self._wrapper_fn)
File "/home/BH/fyn123456/.conda/envs/py36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/computation_wrapper.py", line 96, in _wrap
name=func_name)
File "/home/BH/fyn123456/.conda/envs/py36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/computation_wrapper_instances.py", line 54, in _federated_computation_wrapper_fn
suggested_name=name))
File "/home/BH/fyn123456/.conda/envs/py36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/federated_computation_utils.py", line 75, in zero_or_one_arg_func_to_building_block
parameter_name, parameter_type), context_stack))
File "/home/BH/fyn123456/.conda/envs/py36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/func_utils.py", line 553, in
return (lambda fn, at, kt: lambda arg: _unpack_and_call(fn, at, kt, arg))(
File "/home/BH/fyn123456/.conda/envs/py36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/func_utils.py", line 547, in _unpack_and_call
return func(*args, **kwargs)
File "/home/BH/fyn123456/.conda/envs/py36/lib/python3.6/site-packages/tensorflow_federated/python/learning/framework/optimizer_utils.py", line 394, in run_one_round_tff
client_outputs.model_output)
File "/home/BH/fyn123456/.conda/envs/py36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/func_utils.py", line 642, in call
concrete_fn = self._concrete_function_factory(arg_type)
File "/home/BH/fyn123456/.conda/envs/py36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/computation_wrapper.py", line 85, in
lambda pt: _wrap_polymorphic(wrapper_fn, func, pt))
File "/home/BH/fyn123456/.conda/envs/py36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/computation_wrapper.py", line 82, in _wrap_polymorphic
name=name)
File "/home/BH/fyn123456/.conda/envs/py36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/computation_wrapper_instances.py", line 54, in _federated_computation_wrapper_fn
suggested_name=name))
File "/home/BH/fyn123456/.conda/envs/py36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/federated_computation_utils.py", line 75, in zero_or_one_arg_func_to_building_block
parameter_name, parameter_type), context_stack))
File "/home/BH/fyn123456/.conda/envs/py36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/func_utils.py", line 553, in
return (lambda fn, at, kt: lambda arg: _unpack_and_call(fn, at, kt, arg))(
File "/home/BH/fyn123456/.conda/envs/py36/lib/python3.6/site-packages/tensorflow_federated/python/core/impl/func_utils.py", line 547, in _unpack_and_call
return func(*args, **kwargs)
File "/data/PycharmProjects/federated_learning/test.py", line 60, in aggregate_mnist_metrics_across_clients
'loss': tff.federated_mean(metrics.loss, metrics.num_examples),
AttributeError: module 'tensorflow_federated.python' has no attribute 'federated_mean'

my code:
import collections
import numpy as np
import tensorflow as tf
from tensorflow_federated import python as tff

tf.compat.v1.enable_v2_behavior()

#Defining model variables,forward pass,and metrics
MnistVariables = collections.namedtuple(
'MnistVariables', 'weights bias num_examples loss_sum accuracy_sum')

def create_mnist_variables():
return MnistVariables(
weights = tf.Variable(
lambda: tf.zeros(dtype=tf.float32, shape=(784, 10)),
name='weights',
trainable=True),
bias = tf.Variable(
lambda: tf.zeros(dtype=tf.float32, shape=(10)),
name='bias',
trainable=True),
num_examples = tf.Variable(0.0, name='num_examples', trainable=False),
loss_sum = tf.Variable(0.0, name='loss_sum', trainable=False),
accuracy_sum = tf.Variable(0.0, name='accuracy_sum', trainable=False))

def mnist_forward_pass(variables, batch):
y = tf.nn.softmax(tf.matmul(batch['x'], variables.weights) + variables.bias)
predictions = tf.cast(tf.argmax(y, 1), tf.int32)

flat_labels = tf.reshape(batch['y'], [-1])
loss = -tf.reduce_mean(tf.reduce_sum(
tf.one_hot(flat_labels, 10) * tf.log(y), reduction_indices=[1]))
accuracy = tf.reduce_mean(
tf.cast(tf.equal(predictions, flat_labels), tf.float32))

num_examples = tf.to_float(tf.size(batch['y']))

tf.assign_add(variables.num_examples, num_examples)
tf.assign_add(variables.loss_sum, loss * num_examples)
tf.assign_add(variables.accuracy_sum, accuracy * num_examples)

return loss, predictions

def get_local_mnist_metrics(variables):
return collections.OrderedDict([
('num_examples', variables.num_examples),
('loss', variables.loss_sum / variables.num_examples),
('accuracy', variables.accuracy_sum / variables.num_examples)
])

@tff.federated_computation
def aggregate_mnist_metrics_across_clients(metrics):
return {
'num_examples': tff.federated_sum(metrics.num_examples),
'loss': tff.federated_mean(metrics.loss, metrics.num_examples),
'accuracy': tff.federated_mean(metrics.accuracy, metrics.num_examples)
}

#Constructing an instance of tff.learning.Model
class MnistModel(tff.learning.Model):

def init(self):
self._variables = create_mnist_variables()

@Property
def trainable_variables(self):
return [self._variables.weights, self._variables.bias]

@Property
def non_trainable_variables(self):
return []

@Property
def local_variables(self):
return [
self._variables.num_examples, self._variables.loss_sum,
self._variables.accuracy_sum
]

@Property
def input_spec(self):
return collections.OrderedDict([('x', tf.TensorSpec([None, 784],
tf.float32)),
('y', tf.TensorSpec([None, 1], tf.int32))])

@tf.contrib.eager.function(autograph=False)
def forward_pass(self, batch, training=True):
del training
loss, predictions = mnist_forward_pass(self._variables, batch)
return tff.learning.BatchOutput(loss=loss, predictions=predictions)

@tf.contrib.eager.function(autograph=False)
def report_local_outputs(self):
return get_local_mnist_metrics(self._variables)

@Property
def federated_output_computation(self):
return aggregate_mnist_metrics_across_clients

class MnistTrainableModel(MnistModel, tff.learning.TrainableModel):
.
@tf.contrib.eager.defun(autograph=False)
def train_on_batch(self, batch):
output = self.forward_pass(batch)
optimizer = tf.train.GradientDescentOptimizer(0.02)
optimizer.minimize(output.loss, var_list=self.trainable_variables)
return output

if name=='main':
iterative_process = tff.learning.build_federated_averaging_process(
MnistTrainableModel)

Support for multiple losses with tf.keras

If I understand correctly, tf-federated only supports single loss function. Is there any timeline on when the support for multiple losses will be added?

File "/home/.local/lib/python3.5/site-packages/tensorflow_federated/python/learning/model_utils.py", line 456, in __init__
    raise NotImplementedError('only a single loss functions is supported')

[bug] failure with sgd tests (v0.4.0)

I'm getting AttributeError: 'RefVariable' object has no attribute 'handle' while trying to run test_execute_empty_data from federated_sgd_test.py (either through bazel, or manually, by repeating the code in a project that uses [email protected] ([email protected]). Any help would be great (related to https://stackoverflow.com/questions/56215147/can-i-aggregate-over-gradients-in-tensorflow-federated)

Thank you

full trace:

WARNING:tensorflow:From <user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
Traceback (most recent call last):
  File "D:/PycharmProjects/BSGD/t.py", line 199, in <module>
    test_execute_empty_data()
  File "D:/PycharmProjects/BSGD/t.py", line 178, in test_execute_empty_data
    model_fn=model_examples.LinearRegression)
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow_federated\python\learning\federated_sgd.py", line 161, in build_federated_sgd_process
    model_fn, client_sgd_avg, server_optimizer_fn)
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow_federated\python\learning\framework\optimizer_utils.py", line 345, in build_model_delta_optimizer_process
    @tff.federated_computation
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow_federated\python\core\api\computations.py", line 202, in federated_computation
    return computation_wrapper_instances.federated_computation_wrapper(*args)
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow_federated\python\core\impl\computation_wrapper.py", line 404, in __call__
    self._wrapper_fn)
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow_federated\python\core\impl\computation_wrapper.py", line 97, in _wrap
    name=fn_name)
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow_federated\python\core\impl\computation_wrapper_instances.py", line 54, in _federated_computation_wrapper_fn
    suggested_name=name))
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow_federated\python\core\impl\federated_computation_utils.py", line 78, in zero_or_one_arg_fn_to_building_block
    result = fn()
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow_federated\python\core\impl\function_utils.py", line 463, in <lambda>
    return lambda: fn()  # pylint: disable=unnecessary-lambda
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow_federated\python\learning\framework\optimizer_utils.py", line 349, in server_init_tff
    @tff.tf_computation
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow_federated\python\core\api\computations.py", line 155, in tf_computation
    return computation_wrapper_instances.tensorflow_wrapper(*args)
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow_federated\python\core\impl\computation_wrapper.py", line 404, in __call__
    self._wrapper_fn)
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow_federated\python\core\impl\computation_wrapper.py", line 97, in _wrap
    name=fn_name)
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow_federated\python\core\impl\computation_wrapper_instances.py", line 38, in _tf_wrapper_fn
    target_fn, parameter_type, ctx_stack)
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow_federated\python\core\impl\tensorflow_serialization.py", line 94, in serialize_py_fn_as_tf_computation
    result = target(*args)
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow_federated\python\core\impl\function_utils.py", line 463, in <lambda>
    return lambda: fn()  # pylint: disable=unnecessary-lambda
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow_federated\python\learning\framework\optimizer_utils.py", line 353, in _fn
    stateful_model_broadcast_fn.initialize())
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow_federated\python\learning\framework\optimizer_utils.py", line 222, in server_init
    _, optimizer_vars = _build_server_optimizer(model, optimizer)
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow_federated\python\learning\framework\optimizer_utils.py", line 129, in _build_server_optimizer
    apply_delta(delta=weights_delta)
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 864, in __call__
    graph_function, args, kwargs = self._maybe_define_function(args, kwargs)
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 1176, in _maybe_define_function
    arg_names=arg_names),
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\framework\func_graph.py", line 448, in func_graph_from_py_func
    func_outputs = python_func(*func_args, **func_kwargs)
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow_federated\python\learning\framework\optimizer_utils.py", line 118, in apply_delta
    optimizer.apply_gradients(grads_and_vars, name='server_update')
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\optimizer_v2\optimizer_v2.py", line 364, in apply_gradients
    update_ops.append(update_grad_to_var(grad, var))
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\optimizer_v2\optimizer_v2.py", line 352, in update_grad_to_var
    update_op = self._resource_apply_dense(grad, var)
  File "<user_home>\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\optimizer_v2\gradient_descent.py", line 112, in _resource_apply_dense
    var.handle, lr_t, grad, use_locking=self._use_locking)
AttributeError: 'RefVariable' object has no attribute 'handle'

How adpot other datasets

Hi there, does the current version support other dataset customized by ourselves. The data shown in the tutorials are in HDF5 format and I have a hard time adapting mine to the pipeline.

Memory blow up when using when not flattened image array

Hello,

I am trying to use federated learning for my use case where I already have a densenet121 weights which were built on non-flattened image array as input.

So I tried following the mnist image classification example with some modifications for my use case. But when I do not flatten the image array I run into memory blow up.

Even with 2 training examples per client, my memory of 25GB runs out. The model weights are ~ 28 MB. The dimension of input and output are 240, 240, 3 (for image) and 6 for the label (it is a 6-dimensional vector).

So I am wondering whether there is some memory leak issue when running it without flattening of images in the input.

Thanks.

Operations performed on the communications between the server and clients

Part of federated learning research is based on operations performed on the communications between the server and clients such as dropping part of the updates (drop some gradients describing a model) exchanged between clients and server or discarding an update from a specific client in a certain communication round. I want to know if such capabilities are supported by TFF framework and how they are supported because, from a first look, it seems to me the level of abstraction of TFF API does not allow such operations. Thanks.

Error building the pip package with Bazel

I had a problem building the pip package with Bazel, as below.


(venv) heikos-air:federated hludwig$ mkdir "/tmp/tensorflow_federated"
(venv) heikos-air:federated hludwig$ bazel build `//tensorflow_federated/tools:build_pip_package`
ERROR: /private/var/tmp/_bazel_hludwig/b759d6cfdc3b8fefc6d5ace86fb89267/external/io_bazel_rules_closure/closure/webfiles/web_library.bzl:191:17: Traceback (most recent call last):
	File "/private/var/tmp/_bazel_hludwig/b759d6cfdc3b8fefc6d5ace86fb89267/external/io_bazel_rules_closure/closure/webfiles/web_library.bzl", line 183
		rule(implementation = _web_library, exe..., <2 more arguments>)
	File "/private/var/tmp/_bazel_hludwig/b759d6cfdc3b8fefc6d5ace86fb89267/external/io_bazel_rules_closure/closure/webfiles/web_library.bzl", line 191, in rule
		attr.label_list(cfg = "data", allow_files = True)
Using cfg = "data" on an attribute is a noop and no longer supported. Please remove it. You can use --incompatible_disallow_data_transition=false to temporarily disable this check.
ERROR: error loading package '': in /private/var/tmp/_bazel_hludwig/b759d6cfdc3b8fefc6d5ace86fb89267/external/org_tensorflow/tensorflow/workspace.bzl: in /private/var/tmp/_bazel_hludwig/b759d6cfdc3b8fefc6d5ace86fb89267/external/io_bazel_rules_closure/closure/defs.bzl: Extension file 'closure/webfiles/web_library.bzl' has errors
ERROR: error loading package '': in /private/var/tmp/_bazel_hludwig/b759d6cfdc3b8fefc6d5ace86fb89267/external/org_tensorflow/tensorflow/workspace.bzl: in /private/var/tmp/_bazel_hludwig/b759d6cfdc3b8fefc6d5ace86fb89267/external/io_bazel_rules_closure/closure/defs.bzl: Extension file 'closure/webfiles/web_library.bzl' has errors
INFO: Elapsed time: 0.330s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (0 packages loaded)

It's my first time using Bazel. I had installed it as per instructions but the test had errors. Any thoughts?


(venv) heikos-air:federated hludwig$ bazel test //tensorflow_federated/...
Starting local Bazel server and connecting to it...
ERROR: /private/var/tmp/_bazel_hludwig/b759d6cfdc3b8fefc6d5ace86fb89267/external/io_bazel_rules_closure/closure/webfiles/web_library.bzl:191:17: Traceback (most recent call last):
File "/private/var/tmp/_bazel_hludwig/b759d6cfdc3b8fefc6d5ace86fb89267/external/io_bazel_rules_closure/closure/webfiles/web_library.bzl", line 183
rule(implementation = _web_library, exe..., <2 more arguments>)
File "/private/var/tmp/_bazel_hludwig/b759d6cfdc3b8fefc6d5ace86fb89267/external/io_bazel_rules_closure/closure/webfiles/web_library.bzl", line 191, in rule
attr.label_list(cfg = "data", allow_files = True)
Using cfg = "data" on an attribute is a noop and no longer supported. Please remove it. You can use --incompatible_disallow_data_transition=false to temporarily disable this check.
ERROR: error loading package '': in /private/var/tmp/_bazel_hludwig/b759d6cfdc3b8fefc6d5ace86fb89267/external/org_tensorflow/tensorflow/workspace.bzl: in /private/var/tmp/_bazel_hludwig/b759d6cfdc3b8fefc6d5ace86fb89267/external/io_bazel_rules_closure/closure/defs.bzl: Extension file 'closure/webfiles/web_library.bzl' has errors
ERROR: error loading package '': in /private/var/tmp/_bazel_hludwig/b759d6cfdc3b8fefc6d5ace86fb89267/external/org_tensorflow/tensorflow/workspace.bzl: in /private/var/tmp/_bazel_hludwig/b759d6cfdc3b8fefc6d5ace86fb89267/external/io_bazel_rules_closure/closure/defs.bzl: Extension file 'closure/webfiles/web_library.bzl' has errors
INFO: Elapsed time: 41.430s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (0 packages loaded)
FAILED: Build did NOT complete successfully (0 packages loaded)

Image Classification example without flattening of image array

Hello,

I tried the mnist image classificaiton tutorial. It works. However, when I try running it without flattening of image array I keep the input shape in model creation as:

model = tf.keras.models.Sequential([
tf.keras.layers.Dense(
10,
activation=tf.nn.softmax,
kernel_initializer='zeros',
input_shape=(28,28)
)])

instead of (784,)

But it does not work in this case. The error I get is:

tensorflow.python.framework.errors_impl.InvalidArgumentError: logits and labels must have the same first dimension, got logits shape [448,10] and labels shape [16]
[[{{node loss/dense_loss/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits}}]]

Here 16 is the batch size so 448 is 28 * 16.

Is it not possible to run the example without flattening of images?

Motivation: I already have a model which was built without flattening of images and I am running into some issues while doing federated training on it so I wanted to try image classification tutorial without flattening.

cannot install v0.5.0

that version is not in pypi and trying to install via pip install -e git://github.com/tensorflow/[email protected]#egg=tensorflow_federated

(seems to be missing root setup.py) (using windows)

produces

Obtaining tensorflow_federated from git+git://github.com/tensorflow/[email protected]#egg=tensorflow_federated
  Cloning git://github.com/tensorflow/federated.git (to revision v0.5.0) to my-project\venv\src\tensorflow-federated
  Running command git clone -q git://github.com/tensorflow/federated.git 'my-project\venv\src\tensorflow-federated'
    ERROR: Complete output from command python setup.py egg_info:
    ERROR: Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\my-user\AppData\Local\Programs\Python\Python37\lib\tokenize.py", line 447, in open
        buffer = _builtin_open(filename, 'rb')
    FileNotFoundError: [Errno 2] No such file or directory: my-project\\venv\\src\\tensorflow-federated\\setup.py'
    ----------------------------------------
ERROR: Command "python setup.py egg_info" failed with error code 1 in my-project\venv\src\tensorflow-federated\

Issue of AssignAddVariableOp

Hello,

I'm using TFF, and I've been many errors. I tried to fix, but this error is a bit difficult. Your help is very much appreciated. I posted the code Traceback below, please let me know if I need to post other things.

Your help is most appreciated

Code:

Outputs = tf.convert_to_tensor(np.random.rand(50,1))
input1 = tf.convert_to_tensor(np.random.rand(50,100))
Inputs = input1

    Outputs = tf.cast(Outputs,tf.float32)
    Inputs = tf.cast(Inputs,tf.float32)
    new_batchInput = collections.OrderedDict([('In', Inputs),('Out', Outputs)])

    def generate_one_new_batch():
        yield new_batchInput
    
    dataset_input = tf.data.Dataset.from_tensor_slices(new_batchInput)#,outputs,maxval=100, dtype=tf.float32)
    dataset2 = dataset_input
    Used_dataset= dataset2
    
    def client_data(self,new_dataset):
        def map_fn(elem):
            #return collections.OrderedDict([('x', tf.reshape(elem['In'], [-1])),('y', tf.reshape(elem['Out'],[1]))])
            return collections.OrderedDict([('x', tf.reshape(elem['In'], [-1])),('y', tf.reshape(elem['Out'],[1]))])
        
        DS2= new_dataset.map(map_fn,num_parallel_calls=None)
        
        return DS2.repeat(10).batch(10)
    
    train_data = [client_data(self,Used_dataset)]

    sample_batch = tf.contrib.framework.nest.map_structure(lambda x: x.numpy(), next(iter(train_data[0])))

    def create_SK_model(learning_rate=0.1):
        
        modelF = tf.keras.Sequential([tf.keras.layers.Flatten(input_shape=(100,)),
                                     tf.keras.layers.Dense(10, activation=tf.nn.relu, kernel_initializer='zeros'),
                                     tf.keras.layers.Dense(1, activation=tf.nn.relu, kernel_initializer='zeros'),
                                     ])
        def loss_fn(y_true, y_pred):
            return tf.reduce_mean(tf.keras.losses.mse(y_true, y_pred))

        modelF.compile(loss=tf.keras.losses.mse,optimizer=gradient_descent.SGD(learning_rate))
        return modelF
    
       
    def model_fn():
        return tff.learning.from_compiled_keras_model(create_SK_model(0.1), sample_batch)
    
    YTrain = np.random.rand(50,1)
    XTrain = np.random.rand(50,100)
    
    create_SK_model(0.1).fit(XTrain,YTrain)
    
    trainer = tff.learning.build_federated_averaging_process(model_fn)
    state = trainer.initialize()
    losses = []
    for _ in range(2):
        state, outputs = trainer.next(state, train_data)
        # Track the loss.
        losses.append(outputs.loss)
            
    self.assertLess(losses[1], losses[0])

======================================================
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\framework\ops.py", line 1659, in _create_c_op
c_op = c_api.TF_FinishOperation(op_desc)
tensorflow.python.framework.errors_impl.InvalidArgumentError: Shapes must be equal rank, but are 0 and 1 for 'AssignAddVariableOp' (op: 'AssignAddVariableOp') with input shapes: [], [?].

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\ezalaab.p2\pool\plugins\org.python.pydev.core_7.1.0.201902031515\pysrc\pydevd.py", line 2225, in
main()
File "C:\Users\ezalaab.p2\pool\plugins\org.python.pydev.core_7.1.0.201902031515\pysrc\pydevd.py", line 2218, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Users\ezalaab.p2\pool\plugins\org.python.pydev.core_7.1.0.201902031515\pysrc\pydevd.py", line 1560, in run
return self._exec(is_module, entry_point_fn, module_name, file, globals, locals)
File "C:\Users\ezalaab.p2\pool\plugins\org.python.pydev.core_7.1.0.201902031515\pysrc\pydevd.py", line 1567, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Users\ezalaab.p2\pool\plugins\org.python.pydev.core_7.1.0.201902031515\pysrc_pydev_imps_pydev_execfile.py", line 25, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:\Users\ezalaab\Documents\eclipse-workspace\MANA-FederatedLearning\location-based-federated-learning\Test\FLTF_models_test2.py", line 149, in
FLTest()
File "C:\Users\ezalaab\Documents\eclipse-workspace\MANA-FederatedLearning\location-based-federated-learning\Test\FLTF_models_test2.py", line 143, in init
self.test_self_contained_example()
File "C:\Users\ezalaab\Documents\eclipse-workspace\MANA-FederatedLearning\location-based-federated-learning\Test\FLTF_models_test2.py", line 125, in test_self_contained_example
trainer = tff.learning.build_federated_averaging_process(model_fn)
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\learning\federated_averaging.py", line 148, in build_federated_averaging_process
model_fn, client_fed_avg, server_optimizer_fn)
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\learning\framework\optimizer_utils.py", line 309, in build_model_delta_optimizer_process
federated_dataset_type)
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\core\impl\computation_wrapper.py", line 408, in
return lambda fn: _wrap(fn, arg_type, self._wrapper_fn)
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\core\impl\computation_wrapper.py", line 96, in _wrap
name=fn_name)
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\core\impl\computation_wrapper_instances.py", line 54, in _federated_computation_wrapper_fn
suggested_name=name))
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\core\impl\federated_computation_utils.py", line 75, in zero_or_one_arg_fn_to_building_block
parameter_name, parameter_type), context_stack))
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\core\impl\function_utils.py", line 553, in
return (lambda fn, at, kt: lambda arg: _unpack_and_call(fn, at, kt, arg))(
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\core\impl\function_utils.py", line 547, in _unpack_and_call
return fn(*args, **kwargs)
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\learning\framework\optimizer_utils.py", line 323, in run_one_round_tff
@tff.tf_computation(tf_dataset_type, model_weights_type)
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\core\impl\computation_wrapper.py", line 408, in
return lambda fn: _wrap(fn, arg_type, self._wrapper_fn)
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\core\impl\computation_wrapper.py", line 96, in _wrap
name=fn_name)
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\core\impl\computation_wrapper_instances.py", line 38, in _tf_wrapper_fn
target_fn, parameter_type, ctx_stack)
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\core\impl\tensorflow_serialization.py", line 92, in serialize_py_fn_as_tf_computation
result = target(*args)
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\core\impl\function_utils.py", line 553, in
return (lambda fn, at, kt: lambda arg: _unpack_and_call(fn, at, kt, arg))(
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\core\impl\function_utils.py", line 547, in _unpack_and_call
return fn(*args, **kwargs)
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\learning\framework\optimizer_utils.py", line 344, in client_delta_tf
client_output = client_delta_fn(tf_dataset, initial_model_weights)
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\learning\federated_averaging.py", line 97, in call
initial_state=tf.constant(0.0), reduce_func=reduce_fn)
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 1224, in reduce
add_to_graph=False)
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 2129, in init
self._function._create_definition_if_needed() # pylint: disable=protected-access
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\framework\function.py", line 341, in _create_definition_if_needed
self._create_definition_if_needed_impl()
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\framework\function.py", line 355, in _create_definition_if_needed_impl
whitelisted_stateful_ops=self._whitelisted_stateful_ops)
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\framework\function.py", line 883, in func_graph_from_py_func
outputs = func(*func_graph.inputs)
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 2099, in tf_data_structured_function_wrapper
ret = func(*nested_args)
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\learning\federated_averaging.py", line 91, in reduce_fn
output = model.train_on_batch(batch)
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\learning\model_utils.py", line 544, in train_on_batch
self._model.train_on_batch(batch_input), model_lib.BatchOutput)
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\eager\def_function.py", line 312, in call
canon_args, canon_kwds = self._initialize(args, kwds)
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\eager\def_function.py", line 280, in _initialize
self._stateful_fn._get_concrete_function_internal(*args, **kwds)) # pylint: disable=protected-access
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\eager\function.py", line 876, in _get_concrete_function_internal
graph_function, _, _ = self._maybe_define_function(args, kwargs)
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\eager\function.py", line 1176, in _maybe_define_function
arg_names=arg_names),
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\framework\func_graph.py", line 448, in func_graph_from_py_func
func_outputs = python_func(*func_args, **func_kwargs)
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\eager\def_function.py", line 255, in wrapped_fn
return wrapped_fn.wrapped(*args, **kwds)
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\eager\function.py", line 1652, in bound_method_wrapper
return wrapped_fn(weak_instance(), *args, **kwargs)
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\learning\model_utils.py", line 451, in train_on_batch
batch_output = self._forward_pass(batch_input)
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\learning\model_utils.py", line 382, in _forward_pass
metric.update_state(y_true=y_true, y_pred=predictions)
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\keras\metrics.py", line 98, in decorated
update_op = update_state_fn(*args, **kwargs)
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\learning\model_utils.py", line 321, in update_state
op = self._total_loss.assign_add(batch_total_loss)
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\ops\resource_variable_ops.py", line 881, in assign_add
name=name)
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\ops\gen_resource_variable_ops.py", line 66, in assign_add_variable_op
"AssignAddVariableOp", resource=resource, value=value, name=name)
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 788, in _apply_op_helper
op_def=op_def)
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\framework\func_graph.py", line 281, in create_op
compute_device=compute_device)
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\util\deprecation.py", line 507, in new_func
return func(*args, **kwargs)
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\framework\ops.py", line 3300, in create_op
op_def=op_def)
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\framework\ops.py", line 1823, in init
control_input_ops)
File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\framework\ops.py", line 1662, in _create_c_op
raise ValueError(str(e))
ValueError: Shapes must be equal rank, but are 0 and 1 for 'AssignAddVariableOp' (op: 'AssignAddVariableOp') with input shapes: [], [?].

Can we offer nightly pip packages?

Recently I encounter a problem with the evaluation function in tensorflow federated, as described here.

The answer below says it has been fixed in #309 and will be included in the next release.
I cannot wait for it and thus try to build the pip package from source.
The package built by me works fine on CPU but fails on GPU, and I have no idea what went wrong.

So I hope you can offer official nightly built pip packages.
Thanks.

How to train on multiple GPUs?

Hello,
The model is created with keras, following code is tried to train on 2 gpus:

from tensorflow.keras.utils import multi_gpu_model
model = multi_gpu_model(model, gpus=2)

but get an error:

Traceback (most recent call last):
File "/aiml/code/fl_CNN_train_v0.5.py", line 336, in
iterative_process = tff.learning.build_federated_averaging_process(model_fn)
File "/usr/local/lib/python3.5/dist-packages/tensorflow_federated/python/learning/federated_averaging.py", line 149, in build_federated_averaging_process
model_fn, client_fed_avg, server_optimizer_fn)
File "/usr/local/lib/python3.5/dist-packages/tensorflow_federated/python/learning/framework/optimizer_utils.py", line 286, in build_model_delta_optimizer_process
dummy_model_for_metadata = model_utils.enhance(model_fn())
File "/aiml/code/fl_CNN_train_v0.5.py", line 325, in model_fn
return tff.learning.from_compiled_keras_model(keras_model, sample_batch)
File "/usr/local/lib/python3.5/dist-packages/tensorflow_federated/python/learning/model_utils.py", line 193, in from_compiled_keras_model
return enhance(_TrainableKerasModel(keras_model, dummy_batch))
File "/usr/local/lib/python3.5/dist-packages/tensorflow_federated/python/learning/model_utils.py", line 437, in init
inner_model.test_on_batch(**dummy_batch)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/keras/engine/training.py", line 1253, in test_on_batch
outputs = self.test_function(inputs) # pylint: disable=not-callable
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/keras/backend.py", line 3073, in call
self._make_callable(feed_arrays, feed_symbols, symbol_vals, session)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/keras/backend.py", line 3019, in _make_callable
callable_fn = session._make_callable_from_options(callable_opts)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1471, in _make_callable_from_options
return BaseSession._Callable(self, callable_options)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1425, in init
session._session, options_ptr, status)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/errors_impl.py", line 528, in exit
c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: Tensor conv2d_input:0, specified in either feed_devices or fetch_devices was not found in the Graph
Exception ignored in: <bound method BaseSession._Callable.del of <tensorflow.python.client.session.BaseSession._Callable object at 0x7f53902a8898>>
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1455, in del
self._session._session, self._handle, status)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/errors_impl.py", line 528, in exit
c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: No such callable handle: 444335424

How to train on multiple GPUs using TFF?

The error "ImportError: cannot import name 'computation_pb2'" still appears

Hi!

The error "ImportError: cannot import name 'computation_pb2'" still appears when running
python -c "import tensorflow_federated as tff; print(tff.federated_computation(lambda: 'Hello World')())"

even after installation of TF Federated via Bazel. At the same time running
bazel test tensorflow_federated/python/examples/mnist:models_test
performs well, with no error.

Specs:
MacOS Sierra 10.12
Python 3.6
PyCharm CE 2019 IDE
Conda env

Federated with KerasRegressor?

Hello

I'm trying to get my model of KerasRegressor working with TFF framework. But it seems that "tff.learning.from_compiled_keras_model" does not accept it, right?. My main aim is to differentiate between federated on both regression problem and classification problem.

This is my relevant part of the code:

def create_SK_model():
    modelF = create_SGD_model()
    modelF.compile(loss=tf.keras.losses.MSE,optimizer=tf.keras.optimizers.SGD(lr=learn_rate))
    return modelF
    
def create_Reg_model():
    modelF_Reg = tf.keras.wrappers.scikit_learn.KerasRegressor(build_fn = create_SK_model,nb_epoch=SNN_epoch, batch_size=SNN_batch_size)
        
    return modelF_Reg

def create_Class_model():
    modelF_Reg = tf.keras.wrappers.scikit_learn.KerasClassifier(build_fn = create_SK_model,nb_epoch=SNN_epoch, batch_size=SNN_batch_size)
    return modelF_Class

def create_Single_model():
    if Use_RegClas:
        if Use_Regressor:
            return create_Reg_model()
        elif Use_Classification:
            return create_Class_model()
    else:
        return create_SK_model()
def model_fn_Federated():
    if Use_RegClas:
        if Use_Regressor:
            return tff.learning.from_compiled_keras_model(create_Reg_model,sample_batch)
        elif Use_Classification:
            return tff.learning.from_compiled_keras_model(create_Class_model(),sample_batch)
    elif Use_FLAveraging:
        return tff.learning.from_compiled_keras_model(create_SK_model(),sample_batch)
    else:
        return tff.learning.from_keras_model(create_SGD_model(),sample_batch,loss=tf.keras.losses.MSE)


................... some other code ..................

if Use_FLAveraging:
    trainer_Itr_Process = tff.learning.build_federated_averaging_process(model_fn_Federated,server_optimizer_fn=(lambda : tf.keras.optimizers.SGD(learning_rate=learn_rate)),client_weight_fn=None)
else:
    trainer_Itr_Process = tff.learning.build_federated_sgd_process(model_fn_Federated,server_optimizer_fn=(lambda : tf.keras.optimizers.SGD(learning_rate=learn_rate)),client_weight_fn=None)
    

My main problem is how to incorporate the Regression/classfiication problem into Federated TF framework. I tried the above implementation, correct? wrong? please advice.

Based on the above implementation I get the following error:

.....
    py_typecheck.check_type(keras_model, tf.keras.Model)
  File "/home/..../.local/lib/python3.6/site-packages/tensorflow_federated/python/common_libs/py_typecheck.py", line 48, in check_type
    type_string(type_spec), type_string(type(target))))
TypeError: Expected tensorflow.python.keras.engine.training.Model, found function.

SGD issue

Hello,
I'm getting this error when passing the optimizer to the federated averaging. any help?
I've made sure that the corresponding local model works.

### Code:
`def create_SK_model():
modelF = tf.keras.Sequential([tf.keras.layers.Dense(SNN_Layers[0],activation=tf.nn.relu,input_shape=(Act_Inputs.shape[1],), kernel_initializer='RandomNormal'),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dense(SNN_Layers[1], activation=tf.nn.relu, kernel_initializer='RandomNormal'),
tf.keras.layers.Dense(1, activation=tf.nn.relu, kernel_initializer='RandomNormal'),
])
#modelF.compile(loss=tf.keras.losses.MeanSquaredError(),optimizer=tf.keras.optimizers.SGD(learn_rate))

return modelF

def loss_fn():
return tf.keras.losses.MeanSquaredError()

def model_fn():
return tff.learning.from_keras_model(create_SK_model(),sample_batch,
loss=tf.keras.losses.MeanSquaredError(),
optimizer=tf.keras.optimizers.SGD(lr=learn_rate))

YTrain = Act_Outputs #np.random.rand(50,1)
XTrain = Act_Inputs #np.random.rand(50,100)

locally compile the model

Local_model = create_SK_model()
Local_model.compile(loss=tf.keras.losses.MeanSquaredError(),optimizer=tf.keras.optimizers.SGD(lr=learn_rate,decay=1e-6,momentum=0.9,nesterov=True))

training/fitting with TF federated learning

trainer_Itr_Process = tff.learning.build_federated_averaging_process(model_fn(),server_optimizer_fn=(lambda : tf.keras.optimizers.SGD(lr=learn_rate)),client_weight_fn=None)

### Error:
``Traceback (most recent call last):
File "C:\Users\ezalaab.p2\pool\plugins\org.python.pydev.core_7.1.0.201902031515\pysrc\pydevd.py", line 2225, in
main()
File "C:\Users\ezalaab.p2\pool\plugins\org.python.pydev.core_7.1.0.201902031515\pysrc\pydevd.py", line 2218, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Users\ezalaab.p2\pool\plugins\org.python.pydev.core_7.1.0.201902031515\pysrc\pydevd.py", line 1560, in run
return self._exec(is_module, entry_point_fn, module_name, file, globals, locals)
File "C:\Users\ezalaab.p2\pool\plugins\org.python.pydev.core_7.1.0.201902031515\pysrc\pydevd.py", line 1567, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Users\ezalaab.p2\pool\plugins\org.python.pydev.core_7.1.0.201902031515\pysrc_pydev_imps_pydev_execfile.py", line 25, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:\Users\ezalaab\Documents\eclipse-workspace\MANA-FederatedLearning\location-based-federated-learning\Test\FederatedLearningTFv3.py", line 273, in
trainer_Itr_Process = tff.learning.build_federated_averaging_process(model_fn(),server_optimizer_fn=(lambda : tf.keras.optimizers.SGD(lr=learn_rate)),client_weight_fn=None)
File "C:\Users\ezalaab\Documents\eclipse-workspace\MANA-FederatedLearning\location-based-federated-learning\Test\FederatedLearningTFv3.py", line 264, in model_fn
optimizer=tf.keras.optimizers.SGD(lr=learn_rate))
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\learning\model_utils.py", line 167, in from_keras_model
return enhance(_TrainableKerasModel(keras_model, dummy_batch))
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\learning\model_utils.py", line 442, in init
inner_model.loss_functions[0], inner_model.metrics)
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\learning\model_utils.py", line 336, in init
self.non_trainable_variables,
File "C:\Program Files\Python36\lib\site-packages\tensorflow_federated\python\learning\model_utils.py", line 447, in non_trainable_variables
self._keras_model.optimizer.variables())
AttributeError: 'SGD' object has no attribute 'variables'`

examples/mnist problem

I'm trying mnist example and something happens

During handling of the above exception, another exception occurred: Traceback (most recent call last): File "demo.py", line 26, in <module> trainer = tff.learning.build_federated_averaging_process(model_fn)

图片

Issues with enabling eager execution.

I was following the tutorials included with the repo, The one on https://github.com/tensorflow/federated/blob/master/docs/tutorials/federated_learning_for_image_classification.ipynb to be specific, and on executing
example_element = iter(example_dataset).next()

I got the following error
RuntimeError: dataset.__iter__() is only supported when eager execution is enabled.

While following the tutorial I did run tf.enable_eager_execution(), which didn't return any unusual output, but tf.executing_eagerly() still returns False.

TF Version 1.13.1

Keras set_weights function not working with batch normalization layer in the network

model.set_weights() function from Keras is not working if the network consists of batch normalization layer(s). I looked into the issue, I believe, it is due to having an incorrect order of array elements as returned by tff.learning.keras_weights_from_tff_weights(state.model) function which does not match the output of model.get_weights(). Also, the underlying reason could be that the state.model contains separate tuple for trainable and non-trainable weights.

No 'loss' attribute

I was able to run the Federated Image classification tutorial last week. But now this error is popping:
tff_eror

AttributeError: module 'tensorflow' has no attribute 'function'

Hello,When i execute import tensorflow_federataed as tff,there exist a error:
AttributeError: module 'tensorflow' has no attribute 'function'.
tensorflow_federated vision: 0.4.0;
python vision: 3.5;
tensorflow vision :1.13.1;
Anyone can help me solve this question?

Why TFF runs slowly even with only one client?

I found TFF is extremely slow even if I only simulated with one client. In addition, when I insert tf.print() in function "def call(self, dataset, initial_weights)" in the class ClientFedAvg in federated_averaging.py, running the script in federated_learning_for_image_classification.ipynb will print several times in each round with only one client. But this function should be executed once in each round with each client. I don't know whether it is a bug

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.