Spaces:
Running
Running
File size: 6,890 Bytes
62d807b ca757e2 62d807b ca757e2 62d807b 7cbf317 62d807b c31dd40 62d807b 28cab40 62d807b ca757e2 62d807b c31dd40 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 |
# !usr/bin/env python
# -*- coding:utf-8 -*-
'''
Description :
Version : 1.0
Author : MrYXJ
Mail : yxj2017@gmail.com
Github : https://github.com/MrYxJ
Date : 2023-09-05 23:25:28
LastEditTime : 2023-09-10 17:09:08
Copyright (C) 2023 mryxj. All rights reserved.
'''
import gradio as gr
import pandas as pd
from model_utils import calculate_flops_in_hugging_space
from model_utils import get_mode_from_hf
def get_calclops_result(model_name: str,
input_shape: tuple,
access_token: str,
bp_factor: float,
output_unit: str):
if model_name == "0910":
return [f"# Happy Birthday to You 🎂🎂!", gr.update(visible=False), gr.update(visible=False)]
try:
input_shape = eval(input_shape)
if not isinstance(input_shape, tuple):
raise Exception("Not a tuple.")
except Exception as e:
raise gr.Error(f"Input shape must be a tuple.")
try:
bp_factor = float(bp_factor)
except Exception as e:
raise gr.Error(f"The Factor of Backward as multiple as Forward must be a float.")
if output_unit not in ["", "auto", "T", "G", "M", "K", "m", "u"]:
raise gr.Error(
f"The Output Unit only can be leaved blank or 'T'、'G'、'M'、'K'、'm'、'u'."
)
model = get_mode_from_hf(model_name=model_name,
library="auto",
access_token=access_token)
title = f"## Calculate FLOPs and Params of '{model_name}' "
data, return_print = calculate_flops_in_hugging_space(model_name=model_name,
empty_model=model,
access_token=access_token,
input_shape=input_shape,
bp_factor=bp_factor,
output_unit=output_unit)
return [title, gr.update(visible=True, value=pd.DataFrame(data)), gr.update(visible=True, value=return_print)]
with gr.Blocks() as demo:
with gr.Column():
gr.Markdown(
"""<img src="https://raw.githubusercontent.com/MrYxJ/calculate-flops.pytorch/main/screenshot/calflops_hf3.png?raw=true" style="float: left;" width="250" height="250"><h1> ⛽️Model(Transformers) FLOPs and Parameter Calculator</h1>
This tool is based on the python package [calflops](https://pypi.org/project/calflops/) developed in 🤗Huggingface Space specifically for mainly transformers model to compute FLOPs and Parameters num more convenient.
And calflops is designed to compute the theoretical amount of FLOPs(floating-point operations)、MACs(multiply-add operations) and Parameters in all various neural networks, also including **Transformers(Bert、LlaMA etc Large Language Model) Models** as long as based on the Pytorch implementation,
, which also open source on github, welcome to [star🌟 and use🌟](https://github.com/MrYxJ/calculate-flops.pytorch).
This tool can support the calculation of FLOPs without downloading the parameters of the whole model to the local which is very friendly for large models, but at the same time, this method can only support forward propagation of the model in the `meta` device (Some model implemented operators are not supported on meta device).
Therefore, it is possible that the model operator cannot calculate FLOPs in this way because it does not support calculation on `meta` device, which is that you can also calculate FLOPs by ```pip install calflops``` and download the parameters of the full model to the local.
This tool also support to calculate the FLOPs of model once complete forward + backward pass. According to [epochai report](https://epochai.org/blog/backward-forward-FLOP-ratio), the backward pass of the model FLOPs is default **2** times as much computation as forward pass.
Considering the distributed training of large models, according to [paper](https://arxiv.org/pdf/2205.05198.pdf), if you use parameter activate the recalculation in order to save gpu memory which would make backward pass of models FLOPs would be **3** times as much computation as forward pass.
All in all, you can set the param `Factor of Backward as multiple as Forward` to determine how many times backward pass as much computation as forward pass. Meanwhile this tool supports the printing of FLOPS, Parameter calculation value and proportion of each submodule of the model, it is convient for users to understand the performance consumption of each part of the model and make targeted optimization.
To use this tool pass in the URL or model name on the 🤗HuggingFace Models that you want to calculate the FLOPs and Parameters, you can
select what input shape of model in one step、what times of model backward pass as much comsuption as forward pass and what unit of the calculation result. Finally, this tool is learned from anther good tool [model-memory-usage](https://huggingface.co/spaces/hf-accelerate/model-memory-usage) in the implementation process, 🙏thanks."""
)
out_text = gr.Markdown()
calculate_out = gr.DataFrame(
headers = ["Total Training Params", "Forward FLOPs", "Forward MACs", "Forward+Backward FLOPs", "Forward+Backward MACs"],
interactive=False,
visible=False
)
print_model = gr.Textbox(label=f"Print Each Modules FLOPs、Params", visible=False,
show_legend=True, show_copy_button=True)
with gr.Row():
inp = gr.Textbox(label="Model Name or URL", value="bert-base-cased")
access_token = gr.Textbox(label="API Token", placeholder="Optional (for gated models)")
with gr.Row():
input_shape = gr.Textbox(label="Input Shape, such: (batch, seq_len)", value="(1, 128)")
bp_factor = gr.Textbox(label="Factor of Backward as multiple as Forward", value="2.0")
output_unit = gr.Textbox(label="Outputs Unit, blank means not using unit", value="auto",
placeholder="Optional, leave blank or 'auto','T','G','M','K','m','u'.")
with gr.Row():
btn = gr.Button("Calculate FLOPs and Params")
post_to_hub = gr.Button(
value="Report results in this model repo's discussions!\n(Will open in a new tab)", visible=False
)
btn.click(
get_calclops_result,
inputs=[inp, input_shape, access_token, bp_factor, output_unit],
outputs=[out_text, calculate_out, print_model]
)
demo.launch()
|