<jupyter_start><jupyter_text>In this document we will see how to calculate the FLOPs for KERAS model<jupyter_code>#Install package
#Requirements Python 3.6+ & Tensorflow 2.2+

!pip install keras-flops
#import packages

from tensorflow.keras import Model, Input
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Dropout, Conv2DTranspose,  BatchNormalization, Activation

inp = Input((512, 512, 1))
x = BatchNormalization(input_shape=(512, 512, 1),name='input0',)(inp)

x = Conv2D(8, (3, 3), input_shape=(512, 512, 1), padding='same',strides=(1, 1), activation='relu')(x)
x = Activation('relu')(x)

x = Conv2D(16, (3, 3), input_shape=(512, 512, 1), padding='same',strides=(1, 1), activation='relu')(x)
x = Activation('relu')(x)

x = Conv2DTranspose(32, (3, 3), input_shape=(512, 512, 1), padding='same',strides=(1, 1), activation='relu')(x)
x = Activation('relu')(x)

x = Conv2DTranspose(16, (5, 5), input_shape=(512, 512, 1), padding='same',strides=(1, 1), activation='relu')(x)
x = Activation('relu')(x)

out = Conv2DTranspose(1, (5, 5), input_shape=(512, 512, 1), padding='same',strides=(1, 1), activation='relu',name='output0')(x)
model = Model(inp, out)
model.summary()<jupyter_output>Model: "model_4"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_5 (InputLayer)         [(None, 512, 512, 1)]     0         
_________________________________________________________________
input0 (BatchNormalization)  (None, 512, 512, 1)       4         
_________________________________________________________________
conv2d_4 (Conv2D)            (None, 512, 512, 8)       80        
_________________________________________________________________
activation_12 (Activation)   (None, 512, 512, 8)       0         
_________________________________________________________________
conv2d_5 (Conv2D)            (None, 512, 512, 16)      1168      
_________________________________________________________________
activation_13 (Activation)   (None, 512, 512, 16)      0         
___________________________________________________________[...]<jupyter_text>Note : 1 MACC = 2 Flops (1 Mutlitiplication + 1 Addition)<jupyter_code>from keras_flops import get_flops
flops = get_flops(model, batch_size=1)
print(f"FLOPs: {flops / 10 ** 9:.7} GFlops or BFlops")
print(f"MACCs: {0.5*flops / 10 ** 9:.7} MACCs")<jupyter_output>FLOPs: 9.99791 GFlops or BFlops
MACCs: 4.998955 MACCs<jupyter_text>Tried and not working properly  All the below get_flops function was not working fo the custom developed model shown above<jupyter_code>def get_flops(model_h5_path):
    session = tf.compat.v1.Session()
    graph = tf.compat.v1.get_default_graph()


    with graph.as_default():
        with session.as_default():
            model = tf.keras.models.load_model(model_h5_path)

            run_meta = tf.compat.v1.RunMetadata()
            opts = tf.compat.v1.profiler.ProfileOptionBuilder.float_operation()

            # Optional: save printed results to file
            # flops_log_path = os.path.join(tempfile.gettempdir(), 'tf_flops_log.txt')
            # opts['output'] = 'file:outfile={}'.format(flops_log_path)
            # We use the Keras session graph in the call to the profiler.
            flops = tf.compat.v1.profiler.profile(graph=graph,
                                                  run_meta=run_meta, cmd='op', options=opts)

            return flops.total_float_ops
def get_flops2():
    session = tf.compat.v1.Session()
    graph = tf.compat.v1.get_default_graph()

    with graph.as_default():
        with session.as_default():
            #model = tf.keras.applications.MobileNet(
             #       alpha=1, weights=None, input_tensor=tf.compat.v1.placeholder('float32', shape=(1, 224, 224, 3)))
            model = model1
            run_meta = tf.compat.v1.RunMetadata()
            opts = tf.compat.v1.profiler.ProfileOptionBuilder.float_operation()

            # Optional: save printed results to file
            # flops_log_path = os.path.join(tempfile.gettempdir(), 'tf_flops_log.txt')
            # opts['output'] = 'file:outfile={}'.format(flops_log_path)

            # We use the Keras session graph in the call to the profiler.
            flops = tf.compat.v1.profiler.profile(graph=graph,
                                                  run_meta=run_meta, cmd='op', options=opts)

    tf.compat.v1.reset_default_graph()

    return flops.total_float_ops
# This code is for older version of tensorflow
import tensorflow as tf
import keras.backend as K


def get_flops_0():
    run_meta = tf.RunMetadata()
    opts = tf.profiler.ProfileOptionBuilder.float_operation()

    # We use the Keras session graph in the call to the profiler.
    flops = tf.profiler.profile(graph=K.get_session().graph,
                                run_meta=run_meta, cmd='op', options=opts)

    return flops.total_float_ops  # Prints the "flops" of the model.


# .... Define your model here ....
# You need to have compiled your model before calling this.
print(get_flops_0())<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12894534257120863, 'fraction_numerical': 0.041377983063895306, 'mean_word_length': 3.4995670995670998, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '64722', 'license': 'MIT', 'n_tokens_mistral': 1750, 'n_tokens_neox': 1579, 'n_words': 375, 'path': 'Calculate_FLOPs_MACCs.ipynb', 'repo_name': 'somasundaram1702/Keras', 'size': '5196'}