# Copyright 2024 Flower Labs GmbH. All Rights Reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# =============================================================================="""Mods that report statistics about message communication."""fromloggingimportINFOimportnumpyasnpfromflwr.client.typingimportClientAppCallablefromflwr.common.contextimportContextfromflwr.common.loggerimportlogfromflwr.common.messageimportMessage
[docs]defmessage_size_mod(msg:Message,ctxt:Context,call_next:ClientAppCallable)->Message:"""Message size mod. This mod logs the size in bytes of the message being transmited. """message_size_in_bytes=0forp_recordinmsg.content.parameters_records.values():message_size_in_bytes+=p_record.count_bytes()forc_recordinmsg.content.configs_records.values():message_size_in_bytes+=c_record.count_bytes()form_recordinmsg.content.metrics_records.values():message_size_in_bytes+=m_record.count_bytes()log(INFO,"Message size: %i bytes",message_size_in_bytes)returncall_next(msg,ctxt)
[docs]defparameters_size_mod(msg:Message,ctxt:Context,call_next:ClientAppCallable)->Message:"""Parameters size mod. This mod logs the number of parameters transmitted in the message as well as their size in bytes. """model_size_stats={}parameters_size_in_bytes=0forrecord_name,p_recordinmsg.content.parameters_records.items():p_record_bytes=p_record.count_bytes()parameters_size_in_bytes+=p_record_bytesparameter_count=0forarrayinp_record.values():parameter_count+=(int(np.prod(array.shape))ifarray.shapeelsearray.numpy().size)model_size_stats[f"{record_name}"]={"parameters":parameter_count,"bytes":p_record_bytes,}ifmodel_size_stats:log(INFO,model_size_stats)log(INFO,"Total parameters transmitted: %i bytes",parameters_size_in_bytes)returncall_next(msg,ctxt)