├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── compare.ipynb ├── hub ├── README.md ├── analysis.ipynb ├── model_mapping.py ├── run_all_benchmarks.py └── run_benchmark.py ├── keras_cv ├── README.md ├── analysis.ipynb ├── model_mapping.py ├── run_all_benchmarks.py └── run_benchmark.py ├── keras_legacy ├── README.md ├── analysis.ipynb ├── model_mapping.py ├── run_all_benchmarks.py └── run_benchmark.py └── utilities ├── __init__.py ├── device.py ├── flops.py └── hub.py /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM tensorflow/tensorflow:latest-gpu 2 | 3 | RUN apt-get update && apt-get install -y git 4 | 5 | RUN pip install --no-cache-dir wandb==0.15.3 6 | 7 | CMD ["/bin/bash"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | check_dirs := . 2 | 3 | quality: 4 | black --check $(check_dirs) 5 | ruff $(check_dirs) 6 | 7 | style: 8 | black $(check_dirs) 9 | ruff $(check_dirs) --fix -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # keras-xla-benchmarks 🌪 2 | Presents comprehensive benchmarks of XLA-compatible pre-trained vision models in Keras. We use pre-trained computer vision models shipped by `keras.applications`, `keras_cv.models`, and TensorFlow Hub. Benchmarks were conducted across different image resolutions and different GPU devices (A100, V100, and T4) to provide a holistic overview of the possible gains from XLA. 3 | 4 | Jump straight to the interesting findings [here](https://github.com/sayakpaul/keras-xla-benchmarks#findings-from-the-benchmark-%EF%B8%8F%EF%B8%8F). 5 | 6 | ## Useful links 🌐 7 | 8 | * A [comprehensive report on Weights and Biases](http://wandb.me/keras-xla-benchmark) discussing the benchmarks in details. 9 | * Learn more about XLA from [here](https://www.tensorflow.org/xla). 10 | * You can explore the benchmark results here and interact with them: 11 | [wandb.ai/sayakpaul/keras-xla-benchmarks](https://wandb.ai/sayakpaul/keras-xla-benchmarks). 12 | * The main CSV file collected from the benchmark is available [here](https://huggingface.co/datasets/sayakpaul/keras-xla-benchmarks/blob/main/keras_xla_benchmarks.csv). 13 | * Presentations I have made on XLA: 14 | * [Accelerate your TensorFlow models with XLA](https://docs.google.com/presentation/d/1HbzkdLnT36H3zFTlActwSj6LnH6yegAS0xywStuhqnI/edit?usp=sharing) (focuses on the non-trivial bits needed to be tweaked to make NLP models XLA compatible) 15 | * [Making Keras Models go brrr with XLA](https://docs.google.com/presentation/d/1mM8LeQDpOOLWsMQffRhuDuPPFx4TL-cV848EZtCN_8k/edit?usp=sharing) (focuses on the large-scale benchmark study conducted in this repository) 16 | * A [blog post](https://blog.tensorflow.org/2022/11/how-hugging-face-improved-text-generation-performance-with-xla.html) on how Hugging Face used XLA to speed up the inference latency of its text generation models in 🤗 Transformers. 17 | 18 | ## Model pool 🏊‍♂️ 19 | 20 | Following model families were benchmarked: 21 | 22 | * From `keras.applications` 23 | * [ResNet_V1](https://arxiv.org/abs/1512.03385) 24 | * [ResNet_V2](https://arxiv.org/abs/1603.05027) 25 | * Inception ([one](http://arxiv.org/abs/1512.00567), [two](https://arxiv.org/abs/1602.07261)) 26 | * [ResNetRS](https://arxiv.org/abs/2103.07579) 27 | * [ConvNeXt](https://arxiv.org/abs/2201.03545) 28 | * [EfficientNet_V1](https://arxiv.org/abs/1905.11946) 29 | * [EfficientNet_V2](https://arxiv.org/abs/2104.00298) 30 | * [Xception](https://arxiv.org/abs/1610.02357) 31 | * [MobileNet_V1](https://arxiv.org/abs/1704.04861) 32 | * [MobileNet_V2](https://arxiv.org/abs/1801.04381) 33 | * [MobileNet_V3](https://arxiv.org/abs/1905.02244) 34 | * [VGG](https://arxiv.org/abs/1409.1556) 35 | * [RegNet_X](https://arxiv.org/abs/2003.13678) 36 | * [RegNet_Y](https://arxiv.org/abs/2003.13678) 37 | * [DenseNet](https://arxiv.org/abs/1608.06993) 38 | * [NASNet](https://arxiv.org/abs/1707.07012) 39 | * From `keras_cv.models` 40 | * [YOLOV8](https://arxiv.org/abs/2305.09972) 41 | * [RetinaNet](https://arxiv.org/abs/1708.02002) 42 | * From TensorFlow Hub 43 | * [ViT](https://arxiv.org/abs/2010.11929) 44 | * [DeiT](https://arxiv.org/abs/2012.12877) 45 | * [Swin](https://arxiv.org/abs/2103.14030) 46 | * [MLP-Mixer](https://arxiv.org/abs/2105.01601) 47 | 48 | ## Dev environment 👨‍💻 49 | 50 | Benchmark results can vary a lot from platform. So, it's important ensure a consistent development platform. For the dev environment, we use the following Docker container: `spsayakpaul/keras-xla-benchmarks`, built on top of `tensorflow/tensorflow:latest-gpu` ([reference](https://www.tensorflow.org/install/docker)). 51 | 52 | To run the Docker container: 53 | 54 | ```bash 55 | nvidia-docker run -it --rm --shm-size=16g --ulimit memlock=-1 spsayakpaul/keras-xla-benchmarks 56 | ``` 57 | 58 | For the above command to work, you need to have CUDA and the latest version of Docker installed. You would also need to ensure that you're using a CUDA-compatible GPU. 59 | 60 | Once you're in the Docker image, navigate to any of the model folders (`hub`, `keras_legacy`, or `keras_cv`) and follow the instructions there. 61 | 62 | If you want to log the results to Weights and Biases, install the Python library by running `pip install wandb`. Then while launching a benchmark pass the `--log_wandb` 63 | flag. 64 | 65 | The Docker container was built like so: 66 | 67 | ```bash 68 | docker build -t spsayakpaul/keras-xla-benchmarks . 69 | docker push spsayakpaul/keras-xla-benchmarks 70 | ``` 71 | 72 | ## Findings from the benchmark 🕵️‍♂️ 73 | 74 | Each folder (`keras_legacy`, `keras_cv`, or `hub`) contains a Jupyter Notebook called `analysis.ipynb` that provides some exploratory analysis on the results. The `compare.ipynb` notebook presents some basic analysis as well. 75 | 76 | > 💡 **Note**: that for this project, we solely focus on benchmarking the throughput of the models and NOT on their predictive quality. The benchmarks were conducted using full precision (FP32) and NOT in mixed-precision. The numbers shown below pertain to image classification models only. For numbers on detection models (currently limited to YOLOV8 and RetinaNet), refer to `keras_cv/analysis.ipynb`. 77 | 78 | Below are some findings I found interesting. 79 | 80 | ### Across different GPUs, how fast are the models with XLA from `keras.applications`? 81 | 82 |
83 | 84 | 85 | 86 | 87 | 88 | 89 |
90 | Caption: Throughput (samples/sec) of the top-10 models with XLA across different GPUs. Different GPUs seem to have different top performing models (throughput-wise). The volume of the dots in the plots was determined by the number of parameters each model contains. 91 |

92 | 93 | 💡 One particularly interesting finding here is that models having more FLOPs or more number of parameters aren't always slower than the ones having less FLOPs or less number of parameters. Take the plot corresponding to A100, for example. We notice that VGG16, despite having more FLOPs and more number of parameters, is faster than say, ConvNeXt Tiny. This finding is in line with [The Efficiency Misnomer](https://arxiv.org/abs/2110.12894). Here's another figure further presenting evidence that larger models are always not slower than the smaller ones: 94 | 95 |
96 | 97 | 98 | 99 | 100 | 101 | 102 |
103 | Caption: MobileNet-V3 Small, despite being a much smaller model than MobileNet-V1, is much slower than it when XLA is enabled. 104 |

105 | 106 | ### Resolution-wise distribution of the throughputs obtained by different models in `keras.applications` with XLA 107 | 108 | | | **model_family** | **model_variant** | **resolution** | **accelerator** | **flop (giga)** | **params (million)** | **throughput (samples/sec)** | 109 | |---:|:-----------------|:-----------------|---------------:|:----------------|----------------:|---------------------:|----------------------------:| 110 | | 0 | MobileNet_V1 | mobilenet_v1 | 224 | v100 | 0.57 | 4.25 | 2842.09 | 111 | | 1 | EfficientNet_V2 | efficient_b1_v2 | 240 | v100 | 1.21 | 8.21 | 866.32 | 112 | | 2 | EfficientNet_V2 | efficient_b2_v2 | 260 | v100 | 1.71 | 10.18 | 738.15 | 113 | | 3 | Xception | xception | 299 | a100 | 8.36 | 22.91 | 793.82 | 114 | | 4 | EfficientNet_V1 | efficient_b3 | 300 | a100 | 1.86 | 12.32 | 578.09 | 115 | | 5 | NASNet | nasnet_large | 331 | a100 | 23.84 | 88.95 | 149.77 | 116 | | 6 | EfficientNet_V1 | efficient_b4 | 380 | a100 | 4.46 | 19.47 | 463.45 | 117 | | 7 | EfficientNet_V2 | efficient_s_v2 | 384 | a100 | 8.41 | 21.61 | 474.41 | 118 | | 8 | EfficientNet_V1 | efficient_b5 | 456 | a100 | 10.4 | 30.56 | 268.44 | 119 | | 9 | EfficientNet_V2 | efficient_m_v2 | 480 | a100 | 24.69 | 54.43 | 238.62 | 120 | | 10 | EfficientNet_V1 | efficient_b6 | 528 | a100 | 19.29 | 43.27 | 162.92 | 121 | | 11 | EfficientNet_V1 | efficient_b7 | 600 | a100 | 38.13 | 66.66 | 107.52 | 122 | 123 | 💡 It seems like as we increase the resolution beyond 260, A100 tops the charts. But for resolutions lower than that, V100 tends to yield the highest amount of throughputs with XLA. 124 | 125 | ### What about the same but also grouped w.r.t the GPU being used? 126 | 127 | | | **model_family** | **model_variant** | **resolution** | **accelerator** | **flop (giga)** | **params (million)** | **throughput (samples/sec)** | 128 | |---:|:-------------------|:-------------------|-----------------:|:------------------|-------------------:|-----------------------:|-------------------------------:| 129 | | 0 | MobileNet_V1 | mobilenet_v1 | 224 | a100 | 0.57 | 4.25 | 2608.05 | 130 | | 1 | RegNet_X | regnetx_016 | 224 | t4 | 0.1 | 2.71 | 1921.77 | 131 | | 2 | MobileNet_V1 | mobilenet_v1 | 224 | v100 | 0.57 | 4.25 | 2842.09 | 132 | | 3 | EfficientNet_V1 | efficient_b1 | 240 | a100 | 0.7 | 7.86 | 710.85 | 133 | | 4 | EfficientNet_V2 | efficient_b1_v2 | 240 | t4 | 1.21 | 8.21 | 477.9 | 134 | | 5 | EfficientNet_V2 | efficient_b1_v2 | 240 | v100 | 1.21 | 8.21 | 866.32 | 135 | | 6 | EfficientNet_V1 | efficient_b2 | 260 | a100 | 1.01 | 9.18 | 662.06 | 136 | | 7 | EfficientNet_V2 | efficient_b2_v2 | 260 | t4 | 1.71 | 10.18 | 438.91 | 137 | | 8 | EfficientNet_V2 | efficient_b2_v2 | 260 | v100 | 1.71 | 10.18 | 738.15 | 138 | | 9 | Xception | xception | 299 | a100 | 8.36 | 22.91 | 793.82 | 139 | | 10 | Inception | inception_v3 | 299 | t4 | 5.73 | 23.85 | 224.77 | 140 | | 11 | Xception | xception | 299 | v100 | 8.36 | 22.91 | 467.52 | 141 | | 12 | EfficientNet_V1 | efficient_b3 | 300 | a100 | 1.86 | 12.32 | 578.09 | 142 | | 13 | EfficientNet_V2 | efficient_b3_v2 | 300 | t4 | 3.03 | 14.47 | 283.02 | 143 | | 14 | EfficientNet_V2 | efficient_b3_v2 | 300 | v100 | 3.03 | 14.47 | 515.21 | 144 | | 15 | NASNet | nasnet_large | 331 | a100 | 23.84 | 88.95 | 149.77 | 145 | | 16 | NASNet | nasnet_large | 331 | t4 | 23.84 | 88.95 | 42.37 | 146 | | 17 | NASNet | nasnet_large | 331 | v100 | 23.84 | 88.95 | 104.47 | 147 | | 18 | EfficientNet_V1 | efficient_b4 | 380 | a100 | 4.46 | 19.47 | 463.45 | 148 | | 19 | EfficientNet_V1 | efficient_b4 | 380 | t4 | 4.46 | 19.47 | 131.74 | 149 | | 20 | EfficientNet_V1 | efficient_b4 | 380 | v100 | 4.46 | 19.47 | 310.74 | 150 | | 21 | EfficientNet_V2 | efficient_s_v2 | 384 | a100 | 8.41 | 21.61 | 474.41 | 151 | | 22 | EfficientNet_V2 | efficient_s_v2 | 384 | t4 | 8.41 | 21.61 | 141.84 | 152 | | 23 | EfficientNet_V2 | efficient_s_v2 | 384 | v100 | 8.41 | 21.61 | 323.35 | 153 | | 24 | EfficientNet_V1 | efficient_b5 | 456 | a100 | 10.4 | 30.56 | 268.44 | 154 | | 25 | EfficientNet_V1 | efficient_b5 | 456 | t4 | 10.4 | 30.56 | 47.08 | 155 | | 26 | EfficientNet_V1 | efficient_b5 | 456 | v100 | 10.4 | 30.56 | 173.51 | 156 | | 27 | EfficientNet_V2 | efficient_m_v2 | 480 | a100 | 24.69 | 54.43 | 238.62 | 157 | | 28 | EfficientNet_V2 | efficient_m_v2 | 480 | t4 | 24.69 | 54.43 | 49.26 | 158 | | 29 | EfficientNet_V2 | efficient_m_v2 | 480 | v100 | 24.69 | 54.43 | 133.36 | 159 | | 30 | EfficientNet_V1 | efficient_b6 | 528 | a100 | 19.29 | 43.27 | 162.92 | 160 | | 31 | EfficientNet_V1 | efficient_b6 | 528 | t4 | 19.29 | 43.27 | 36.88 | 161 | | 32 | EfficientNet_V1 | efficient_b6 | 528 | v100 | 19.29 | 43.27 | 104.09 | 162 | | 33 | EfficientNet_V1 | efficient_b7 | 600 | a100 | 38.13 | 66.66 | 107.52 | 163 | | 34 | EfficientNet_V1 | efficient_b7 | 600 | t4 | 38.13 | 66.66 | 20.85 | 164 | | 35 | EfficientNet_V1 | efficient_b7 | 600 | v100 | 38.13 | 66.66 | 63.23 | 165 | 166 | 💡 So, the fastest model changes for a fixed resolution when the GPU (being used for benchmarking) changes. This phenomena becomes less evident when the resolution increases. 167 | 168 | ### Which model family (from `keras.applications`) has the highest amount of absolute speedup from XLA for a particular resolution (say 224) and accelerator (say A100)? 169 | 170 | | | model_family | model_variant | speedup | 171 | |---:|:----------------|:-------------------|----------:| 172 | | 0 | ConvNeXt | convnext_tiny | 1134.46 | 173 | | 1 | DenseNet | densenet_121 | 700.73 | 174 | | 2 | EfficientNet_V1 | efficient_b0 | 893.08 | 175 | | 3 | EfficientNet_V2 | efficient_b0_v2 | 780 | 176 | | 4 | MobileNet_V1 | mobilenet_v1 | 2543.92 | 177 | | 5 | MobileNet_V2 | mobilenet_v2 | 1668.39 | 178 | | 6 | MobileNet_V3 | mobilenet_v3_small | 1600.67 | 179 | | 7 | NASNet | nasnet_mobile | 423.78 | 180 | | 8 | RegNet_X | regnetx_016 | 1933.78 | 181 | | 9 | RegNet_Y | regnety_002 | 1216.29 | 182 | | 10 | ResNetRS | resnetrs_50 | 787.59 | 183 | | 11 | ResNet_V1 | resnet50_v1 | 671.24 | 184 | | 12 | ResNet_V2 | resnet101_v2 | 569.12 | 185 | | 13 | VGG | vgg16 | 1209.08 | 186 | 187 | 💡 Absolute speedup here means `throughput_with_xla` - `throughput_without_xla`. Interestingly, for each model family, the smallest model doesn't necessarily always lead to the highest amount of absolute speedup. For example, for RegNetX, RegNetX_16 isn't the smallest variant. Same holds for ResNet101_V2. 188 | 189 | ### What about the relative speedup in percentages? 190 | 191 | | | model_family | model_variant | speedup_percentage | 192 | |---:|:----------------|:-------------------|---------------------:| 193 | | 0 | ConvNeXt | convnext_small | 4188.45 | 194 | | 1 | DenseNet | densenet_121 | 3686.11 | 195 | | 2 | EfficientNet_V1 | efficient_b0 | 2841.49 | 196 | | 3 | EfficientNet_V2 | efficient_b0_v2 | 2761.06 | 197 | | 4 | MobileNet_V1 | mobilenet_v1 | 3966.82 | 198 | | 5 | MobileNet_V2 | mobilenet_v2 | 2964.45 | 199 | | 6 | MobileNet_V3 | mobilenet_v3_small | 3878.53 | 200 | | 7 | NASNet | nasnet_mobile | 4368.87 | 201 | | 8 | RegNet_X | regnetx_016 | 4452.64 | 202 | | 9 | RegNet_Y | regnety_004 | 3427.97 | 203 | | 10 | ResNetRS | resnetrs_350 | 3300.45 | 204 | | 11 | ResNet_V1 | resnet152_v1 | 1639.69 | 205 | | 12 | ResNet_V2 | resnet101_v2 | 2844.18 | 206 | | 13 | VGG | vgg16 | 396.472 | 207 | 208 | 💡 Some whopping speedup (**4452.64%**) right there 🤯 Again, smallest variant from a model family doesn't always lead to the highest amount of relative speedup here. 209 | 210 | ### How do these models fair to non-CNN models such as Swin, ViT, DeiT, and MLP-Mixer? 211 | 212 | | | model_family | model_variant | speedup_percentage | 213 | |---:|:----------------|:---------------------------------|---------------------:| 214 | | 0 | RegNet_X | regnetx_016 | 4452.64 | 215 | | 1 | NASNet | nasnet_mobile | 4368.87 | 216 | | 2 | ConvNeXt | convnext_small | 4188.45 | 217 | | 3 | MobileNet_V1 | mobilenet_v1 | 3966.82 | 218 | | 4 | DenseNet | densenet_121 | 3686.11 | 219 | | 5 | RegNet_Y | regnety_004 | 3427.97 | 220 | | 6 | ResNetRS | resnetrs_350 | 3300.45 | 221 | | 7 | MobileNet_V2 | mobilenet_v2 | 2964.45 | 222 | | 8 | ResNet_V2 | resnet101_v2 | 2844.18 | 223 | | 9 | EfficientNet_V1 | efficient_b0 | 2841.49 | 224 | | 10 | EfficientNet_V2 | efficient_b0_v2 | 2761.06 | 225 | | 11 | ResNet_V1 | resnet152_v1 | 1639.69 | 226 | | 12 | Swin | swin_s3_small_224 | 1382.65 | 227 | | 13 | DeiT | deit_small_distilled_patch16_224 | 525.086 | 228 | | 14 | VGG | vgg16 | 396.472 | 229 | | 15 | MLP-Mixer | mixer_b32 | 75.1291 | 230 | | 16 | ViT | vit_b16 | 5.69305 | 231 | 232 | 💡 Seems like the non-CNN models don't benefit as much in comparison to the CNN ones from XLA. 233 | 234 | ### Within non-CNN models, what's the trend? 235 | 236 |
237 | 238 | 239 | 240 | 241 | 242 | 243 |
244 | Caption: Throughput (samples/sec) of the top-10 non-CNN models with XLA across different GPUs. Different GPUs seem to have different top performing models (throughput-wise). The volume of the dots in the plots was determined by the number of parameters each model contains. 245 |

246 | 247 | 💡 Here also the similar finding holds as the one presented after Table 1. Mixer-B32, despite being much larger than many models, is faster than the other variants. 248 | 249 | ### Explore these benchmarks interactively 250 | 251 | You are welcome to explore these benchmarks in more details interactively on Weights and Biases via [this report](http://wandb.me/keras-xla-benchmark). 252 | 253 | ![keras-xla-benchmarks](https://github.com/sayakpaul/keras-xla-benchmarks/assets/22957388/10a1ac24-d8a8-4446-b742-372ac14ae772) 254 | 255 | Plus the plots there look extremely cool 🤷 256 | 257 | 258 | 259 | 260 | 263 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 275 | 278 | 279 | 280 | 281 | 282 | 283 | 284 |
261 | 262 | 264 | 265 |
Log throughput of all modelsThroughput of all models
grouped by model family
273 | 274 | 276 | 277 |
Parallel coordinates plot
of correlations to XLA
Throughput of models
grouped by GPU device
285 | 286 | ## Keep in mind 🧠 287 | 288 | When you compile a model into XLA, always ensure the outputs of the compiled 289 | model match with the non-compiled model. Here is an example: 290 | 291 | ```py 292 | import tensorflow as tf 293 | import numpy as np 294 | 295 | model = tf.keras.applications.MobileNetV3Large() 296 | random_inputs = tf.random.normal((4, 224, 224, 3)) 297 | 298 | model_call_fn = tf.function(model, jit_compile=True) 299 | 300 | non_xla_outs = model.predict(random_inputs) 301 | xla_outs = model_call_fn(random_inputs, training=False) 302 | 303 | np.testing.assert_allclose( 304 | non_xla_outs, 305 | xla_outs.numpy(), 306 | atol=1e-5, 307 | rtol=1e-5 308 | ) 309 | ``` 310 | 311 | ## Acknowledgements 312 | 313 | Huge shoutout to [Soumik Rakshit](https://in.linkedin.com/in/soumikrakshit) and [Ayush Thakur](https://in.linkedin.com/in/ayush-thakur-731914149) from the Weights and Biases team for helping a lot with the report. Soumik wrote most of it while Ayush helped with Weave plots. 314 | -------------------------------------------------------------------------------- /compare.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "id": "dd5ad2be", 7 | "metadata": {}, 8 | "outputs": [], 9 | "source": [ 10 | "# Install `wandb` by running `pip install wandb`.\n", 11 | "# and then run `!wandb login`.\n", 12 | "import wandb\n", 13 | "\n", 14 | "api = wandb.Api()\n", 15 | "entity, project = \"sayakpaul\", \"keras-xla-benchmarks\" \n", 16 | "runs = api.runs(entity + \"/\" + project) \n", 17 | "print(f\"Total runs: {len(runs)}\")" 18 | ] 19 | }, 20 | { 21 | "cell_type": "code", 22 | "execution_count": null, 23 | "id": "088fc366", 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "import pandas as pd\n", 28 | "\n", 29 | "resolutions = []\n", 30 | "accelerators = []\n", 31 | "\n", 32 | "model_families = []\n", 33 | "model_variants = []\n", 34 | "xla_status = []\n", 35 | "\n", 36 | "flops = []\n", 37 | "params = []\n", 38 | "throughputs = []\n", 39 | "\n", 40 | "for run in runs:\n", 41 | " if run.name != \"benchmark-summary\":\n", 42 | " run_config = run.config\n", 43 | " run_summary = run.summary._json_dict\n", 44 | "\n", 45 | " model_families.append(run_config[\"family\"])\n", 46 | " model_variants.append(run_config[\"variant\"])\n", 47 | " resolutions.append(run_config[\"resolution\"])\n", 48 | " xla_status.append(run_config[\"xla\"])\n", 49 | "\n", 50 | " accelerator_name = run.name.split(\"@\")[-1].split(\"-\")[1]\n", 51 | " accelerators.append(accelerator_name)\n", 52 | "\n", 53 | " flops.append(run_summary[\"FLOPs (giga)\"])\n", 54 | " params.append(run_summary[\"Num parameters (million)\"])\n", 55 | " throughputs.append(run_summary[\"Throughput (samples/sec)\"])\n", 56 | "\n", 57 | "viz_df = pd.DataFrame(\n", 58 | " {\n", 59 | " \"model_family\": model_families,\n", 60 | " \"model_variant\": model_variants,\n", 61 | " \"resolution\": resolutions,\n", 62 | " \"xla\": xla_status,\n", 63 | " \"accelerator\": accelerators,\n", 64 | " \"flop (giga)\": flops,\n", 65 | " \"params (million)\": params,\n", 66 | " \"throughput (samples/sec)\": throughputs,\n", 67 | " }\n", 68 | ")\n", 69 | "viz_df.head()" 70 | ] 71 | }, 72 | { 73 | "cell_type": "code", 74 | "execution_count": null, 75 | "id": "0e67fdf4", 76 | "metadata": {}, 77 | "outputs": [], 78 | "source": [ 79 | "viz_df.to_csv(\"keras_xla_benchmarks.csv\", index=False)" 80 | ] 81 | }, 82 | { 83 | "cell_type": "code", 84 | "execution_count": null, 85 | "id": "ae45cfc9", 86 | "metadata": {}, 87 | "outputs": [], 88 | "source": [ 89 | "# For the CNN model families, which one is the best?\n", 90 | "# What about model families?\n", 91 | "grouped = viz_df.groupby([\"resolution\", \"model_family\", \"accelerator\"])[\n", 92 | " \"throughput (samples/sec)\"\n", 93 | "].idxmax()\n", 94 | "result = viz_df.loc[grouped, viz_df.columns]\n", 95 | "result" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": null, 101 | "id": "f422cad6", 102 | "metadata": {}, 103 | "outputs": [], 104 | "source": [ 105 | "result[result[\"accelerator\"] == \"a100\"].sort_values(\n", 106 | " by=[\"throughput (samples/sec)\"], ascending=False\n", 107 | ")" 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": null, 113 | "id": "676dce5a", 114 | "metadata": {}, 115 | "outputs": [], 116 | "source": [ 117 | "result.query(\"resolution == 224 and accelerator == 'a100'\").sort_values(\n", 118 | " by=[\"throughput (samples/sec)\"], ascending=False\n", 119 | ")" 120 | ] 121 | }, 122 | { 123 | "cell_type": "code", 124 | "execution_count": null, 125 | "id": "cb12fa23", 126 | "metadata": {}, 127 | "outputs": [], 128 | "source": [ 129 | "# Adapted from\n", 130 | "# https://github.com/nlp-with-transformers/notebooks/blob/main/08_model-compression.ipynb\n", 131 | "\n", 132 | "import matplotlib.pyplot as plt\n", 133 | "\n", 134 | "\n", 135 | "def plot_metrics(df, savefig=False):\n", 136 | " for model_variant in df[\"model_variant\"]:\n", 137 | " filtered = df.query(f\"model_variant == '{model_variant}'\")\n", 138 | " plt.scatter(\n", 139 | " filtered[\"flop (giga)\"],\n", 140 | " filtered[\"throughput (samples/sec)\"],\n", 141 | " alpha=0.5,\n", 142 | " s=filtered[\"params (million)\"] * 5,\n", 143 | " label=model_variant,\n", 144 | " marker=\"o\",\n", 145 | " )\n", 146 | "\n", 147 | " legend = plt.legend(bbox_to_anchor=(1, 1))\n", 148 | " for handle in legend.legendHandles:\n", 149 | " handle.set_sizes([20])\n", 150 | "\n", 151 | " plt.ylabel(\"Throughput (samples/sec)\", fontsize=14)\n", 152 | " plt.xlabel(\"FLOPS (giga)\", fontsize=14)\n", 153 | "\n", 154 | " accelerator_name = df[\"accelerator\"].unique()[0]\n", 155 | " resolution = df[\"resolution\"].unique()[0]\n", 156 | " xla_status = df[\"xla\"].unique()[0]\n", 157 | " plt.title(\n", 158 | " f\"Accelerator: {accelerator_name}, Resolution: {resolution}, XLA: {xla_status}\",\n", 159 | " fontsize=14,\n", 160 | " )\n", 161 | " if not savefig:\n", 162 | " plt.show()\n", 163 | " else:\n", 164 | " plot_name = f\"{accelerator_name}_{resolution}_{xla_status}.png\"\n", 165 | " plt.savefig(plot_name, dpi=300, bbox_inches=\"tight\")" 166 | ] 167 | }, 168 | { 169 | "cell_type": "code", 170 | "execution_count": null, 171 | "id": "340bb8d7", 172 | "metadata": {}, 173 | "outputs": [], 174 | "source": [ 175 | "df_224_a100 = result.query(\"resolution == 224 and accelerator == 'a100'\")\n", 176 | "\n", 177 | "plot_metrics(df_224_a100)" 178 | ] 179 | }, 180 | { 181 | "cell_type": "code", 182 | "execution_count": null, 183 | "id": "a60f9331", 184 | "metadata": {}, 185 | "outputs": [], 186 | "source": [ 187 | "df_224_v100 = result.query(\"resolution == 224 and accelerator == 'v100'\")\n", 188 | "\n", 189 | "plot_metrics(df_224_v100)" 190 | ] 191 | }, 192 | { 193 | "cell_type": "code", 194 | "execution_count": null, 195 | "id": "0c571b78", 196 | "metadata": {}, 197 | "outputs": [], 198 | "source": [ 199 | "df_224_t4 = result.query(\"resolution == 224 and accelerator == 't4'\")\n", 200 | "\n", 201 | "plot_metrics(df_224_t4)" 202 | ] 203 | } 204 | ], 205 | "metadata": { 206 | "kernelspec": { 207 | "display_name": "Python 3 (ipykernel)", 208 | "language": "python", 209 | "name": "python3" 210 | }, 211 | "language_info": { 212 | "codemirror_mode": { 213 | "name": "ipython", 214 | "version": 3 215 | }, 216 | "file_extension": ".py", 217 | "mimetype": "text/x-python", 218 | "name": "python", 219 | "nbconvert_exporter": "python", 220 | "pygments_lexer": "ipython3", 221 | "version": "3.8.2" 222 | } 223 | }, 224 | "nbformat": 4, 225 | "nbformat_minor": 5 226 | } 227 | -------------------------------------------------------------------------------- /hub/README.md: -------------------------------------------------------------------------------- 1 | ## Running the benchmarks 2 | 3 | We leverage TensorFlow Hub to benchmark the following models: 4 | 5 | * [ViT](https://arxiv.org/abs/2010.11929) 6 | * [DeiT](https://arxiv.org/abs/2012.12877) 7 | * [Swin](https://arxiv.org/abs/2103.14030) 8 | * [MLP-Mixer](https://arxiv.org/abs/2105.01601) 9 | 10 | You can launch benchmarks in bulk by running `python run_all_benchmarks.py`. To run 11 | a benchmark individually, run `python run_benchmark.py`. If you do `python run_benchmark.py -h`, you will be able to see the CLI arguments supported by the script. 12 | 13 | 14 | ## FLOPs 15 | 16 | FLOPs count for the ViT and MLP-Mixer models were derived with `timm` and `fvcore` using the following code: 17 | 18 | ```python 19 | import timm 20 | import torch 21 | from fvcore.nn import FlopCountAnalysis, flop_count_str, flop_count_table 22 | 23 | random_input = torch.randn(1, 3, 224, 224) 24 | 25 | 26 | def print_flops(model_names: list): 27 | for name in model_names: 28 | print("*" * 80) 29 | print(name) 30 | if name != "mixer_b32_224": 31 | model = timm.create_model(name, pretrained=True) 32 | else: 33 | model = timm.create_model(name) 34 | flop = FlopCountAnalysis(model, random_input) 35 | print(flop_count_table(flop, max_depth=1)) 36 | print("*" * 80) 37 | print("\n") 38 | 39 | 40 | vit_models_timm = [ 41 | "vit_small_patch16_224", 42 | "vit_base_patch8_224", 43 | "vit_base_patch16_224", 44 | "vit_base_patch32_224", 45 | "vit_large_patch16_224", 46 | "vit_small_r26_s32_224", 47 | "vit_large_r50_s32_224", 48 | ] 49 | print_flops(vit_models_timm) 50 | 51 | mixer_models_timm = ["mixer_b16_224", "mixer_b32_224", "mixer_l16_224"] 52 | print_flops(mixer_models_timm) 53 | ``` 54 | 55 | 56 | -------------------------------------------------------------------------------- /hub/analysis.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "id": "c37536c6", 7 | "metadata": {}, 8 | "outputs": [], 9 | "source": [ 10 | "# Install wandb by `pip install wandb`. \n", 11 | "# And then run `!wandb login`.\n", 12 | "import wandb\n", 13 | "\n", 14 | "api = wandb.Api()\n", 15 | "entity, project = \"sayakpaul\", \"keras-xla-benchmarks\" \n", 16 | "runs = api.runs(entity + \"/\" + project) \n", 17 | "print(f\"Total runs: {len(runs)}\")" 18 | ] 19 | }, 20 | { 21 | "cell_type": "code", 22 | "execution_count": null, 23 | "id": "2e4fb501", 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "from model_mapping import MODEL_NAME_MAPPING\n", 28 | "\n", 29 | "all_variants = [\n", 30 | " variant for k in MODEL_NAME_MAPPING for variant in MODEL_NAME_MAPPING[k]\n", 31 | "]\n", 32 | "all_variants" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": null, 38 | "id": "ab5e465d", 39 | "metadata": {}, 40 | "outputs": [], 41 | "source": [ 42 | "import pandas as pd\n", 43 | "\n", 44 | "resolutions = []\n", 45 | "accelerators = []\n", 46 | "\n", 47 | "model_families = []\n", 48 | "model_variants = []\n", 49 | "xla_status = []\n", 50 | "\n", 51 | "flops = []\n", 52 | "params = []\n", 53 | "throughputs = []\n", 54 | "\n", 55 | "for run in runs:\n", 56 | " if run.name != \"benchmark-summary\":\n", 57 | " run_config = run.config\n", 58 | " run_summary = run.summary._json_dict\n", 59 | "\n", 60 | " if run_config[\"variant\"] in all_variants:\n", 61 | " model_families.append(run_config[\"family\"])\n", 62 | " model_variants.append(run_config[\"variant\"])\n", 63 | " resolutions.append(run_config[\"resolution\"])\n", 64 | " xla_status.append(run_config[\"xla\"])\n", 65 | "\n", 66 | " accelerator_name = run.name.split(\"@\")[-1].split(\"-\")[1]\n", 67 | " accelerators.append(accelerator_name)\n", 68 | "\n", 69 | " flops.append(run_summary[\"FLOPs (giga)\"])\n", 70 | " params.append(run_summary[\"Num parameters (million)\"])\n", 71 | " throughputs.append(run_summary[\"Throughput (samples/sec)\"])\n", 72 | "\n", 73 | "viz_df = pd.DataFrame(\n", 74 | " {\n", 75 | " \"model_family\": model_families,\n", 76 | " \"model_variant\": model_variants,\n", 77 | " \"resolution\": resolutions,\n", 78 | " \"xla\": xla_status,\n", 79 | " \"accelerator\": accelerators,\n", 80 | " \"flop (giga)\": flops,\n", 81 | " \"params (million)\": params,\n", 82 | " \"throughput (samples/sec)\": throughputs,\n", 83 | " }\n", 84 | ")\n", 85 | "viz_df.head()" 86 | ] 87 | }, 88 | { 89 | "cell_type": "code", 90 | "execution_count": null, 91 | "id": "677dc1e2", 92 | "metadata": {}, 93 | "outputs": [], 94 | "source": [ 95 | "def plot_topk_per_accelerator(\n", 96 | " accelerator=\"a100\", topk=10, resolution=224, xla_status=True\n", 97 | "):\n", 98 | " filtered_df = viz_df[viz_df[\"accelerator\"] == accelerator]\n", 99 | " subset_df = filtered_df.query(f\"resolution == {resolution} and xla == {xla_status}\")\n", 100 | " topk_df = subset_df.nlargest(topk, [\"throughput (samples/sec)\"])\n", 101 | " return topk_df" 102 | ] 103 | }, 104 | { 105 | "cell_type": "code", 106 | "execution_count": null, 107 | "id": "9c5ff12d", 108 | "metadata": {}, 109 | "outputs": [], 110 | "source": [ 111 | "# Adapted from\n", 112 | "# https://github.com/nlp-with-transformers/notebooks/blob/main/08_model-compression.ipynb\n", 113 | "\n", 114 | "import matplotlib.pyplot as plt\n", 115 | "\n", 116 | "\n", 117 | "def plot_metrics(df, savefig=False):\n", 118 | " for model_variant in df[\"model_variant\"]:\n", 119 | " filtered = df.query(f\"model_variant == '{model_variant}'\")\n", 120 | " plt.scatter(\n", 121 | " filtered[\"flop (giga)\"],\n", 122 | " filtered[\"throughput (samples/sec)\"],\n", 123 | " alpha=0.5,\n", 124 | " s=filtered[\"params (million)\"] * 5,\n", 125 | " label=model_variant,\n", 126 | " marker=\"o\",\n", 127 | " )\n", 128 | "\n", 129 | " legend = plt.legend(bbox_to_anchor=(1, 1))\n", 130 | " for handle in legend.legendHandles:\n", 131 | " handle.set_sizes([20])\n", 132 | "\n", 133 | " plt.ylabel(\"Throughput (samples/sec)\", fontsize=14)\n", 134 | " plt.xlabel(\"FLOPS (giga)\", fontsize=14)\n", 135 | "\n", 136 | " accelerator_name = df[\"accelerator\"].unique()[0]\n", 137 | " resolution = df[\"resolution\"].unique()[0]\n", 138 | " xla_status = df[\"xla\"].unique()[0]\n", 139 | " plt.title(\n", 140 | " f\"Accelerator: {accelerator_name}, Resolution: {resolution}, XLA: {xla_status}\",\n", 141 | " fontsize=14,\n", 142 | " )\n", 143 | " if not savefig:\n", 144 | " plt.show()\n", 145 | " else:\n", 146 | " plot_name = f\"{accelerator_name}_{resolution}_{xla_status}.png\"\n", 147 | " plt.savefig(plot_name, dpi=300, bbox_inches=\"tight\")" 148 | ] 149 | }, 150 | { 151 | "cell_type": "code", 152 | "execution_count": null, 153 | "id": "38d838bd", 154 | "metadata": {}, 155 | "outputs": [], 156 | "source": [ 157 | "a100_df = plot_topk_per_accelerator(\"a100\")\n", 158 | "plot_metrics(a100_df)" 159 | ] 160 | }, 161 | { 162 | "cell_type": "code", 163 | "execution_count": null, 164 | "id": "12f0007d", 165 | "metadata": {}, 166 | "outputs": [], 167 | "source": [ 168 | "v100_df = plot_topk_per_accelerator(\"v100\")\n", 169 | "plot_metrics(v100_df)" 170 | ] 171 | }, 172 | { 173 | "cell_type": "code", 174 | "execution_count": null, 175 | "id": "efefba62", 176 | "metadata": {}, 177 | "outputs": [], 178 | "source": [ 179 | "t4_df = plot_topk_per_accelerator(\"t4\")\n", 180 | "plot_metrics(t4_df)" 181 | ] 182 | }, 183 | { 184 | "cell_type": "code", 185 | "execution_count": null, 186 | "id": "dc9d6d7f", 187 | "metadata": {}, 188 | "outputs": [], 189 | "source": [ 190 | "viz_df.resolution.unique()" 191 | ] 192 | }, 193 | { 194 | "cell_type": "code", 195 | "execution_count": null, 196 | "id": "78f775cf", 197 | "metadata": {}, 198 | "outputs": [], 199 | "source": [ 200 | "# Grouping the dataframe by unique resolutions and finding the \n", 201 | "# model variant with highest throughput per group.\n", 202 | "grouped = viz_df.groupby(\"resolution\")[\"throughput (samples/sec)\"].idxmax()\n", 203 | "\n", 204 | "# Selecting the rows with the highest throughput per group.\n", 205 | "result = viz_df.loc[grouped, viz_df.columns]\n", 206 | "result" 207 | ] 208 | }, 209 | { 210 | "cell_type": "code", 211 | "execution_count": null, 212 | "id": "06a9026d", 213 | "metadata": {}, 214 | "outputs": [], 215 | "source": [ 216 | "grouped = viz_df.groupby([\"resolution\", \"accelerator\"])[\n", 217 | " \"throughput (samples/sec)\"\n", 218 | "].idxmax()\n", 219 | "result = viz_df.loc[grouped, viz_df.columns]\n", 220 | "result" 221 | ] 222 | }, 223 | { 224 | "cell_type": "code", 225 | "execution_count": null, 226 | "id": "8392e8d6", 227 | "metadata": {}, 228 | "outputs": [], 229 | "source": [ 230 | "# What about model families?\n", 231 | "grouped = viz_df.groupby([\"resolution\", \"model_family\", \"accelerator\"])[\n", 232 | " \"throughput (samples/sec)\"\n", 233 | "].idxmax()\n", 234 | "result = viz_df.loc[grouped, viz_df.columns]\n", 235 | "result" 236 | ] 237 | } 238 | ], 239 | "metadata": { 240 | "kernelspec": { 241 | "display_name": "Python 3 (ipykernel)", 242 | "language": "python", 243 | "name": "python3" 244 | }, 245 | "language_info": { 246 | "codemirror_mode": { 247 | "name": "ipython", 248 | "version": 3 249 | }, 250 | "file_extension": ".py", 251 | "mimetype": "text/x-python", 252 | "name": "python", 253 | "nbconvert_exporter": "python", 254 | "pygments_lexer": "ipython3", 255 | "version": "3.8.2" 256 | } 257 | }, 258 | "nbformat": 4, 259 | "nbformat_minor": 5 260 | } 261 | -------------------------------------------------------------------------------- /hub/model_mapping.py: -------------------------------------------------------------------------------- 1 | MODEL_NAME_MAPPING = { 2 | "ViT": { 3 | "vit_s16": ("https://tfhub.dev/sayakpaul/vit_s16_classification/1", 4.251), 4 | "vit_b8": ("https://tfhub.dev/sayakpaul/vit_b8_classification/1", 66.865), 5 | "vit_b16": ("https://tfhub.dev/sayakpaul/vit_b16_classification/1", 16.867), 6 | "vit_b32": ("https://tfhub.dev/sayakpaul/vit_b32_classification/1", 4.368), 7 | "vit_l16": ("https://tfhub.dev/sayakpaul/vit_l16_classification/1", 59.697), 8 | "vit_r26_s32": ( 9 | "https://tfhub.dev/sayakpaul/vit_r26_s32_lightaug_classification/1", 10 | 3.536, 11 | ), 12 | "vit_r50_l32": ( 13 | "https://tfhub.dev/sayakpaul/vit_r50_l32_classification/1", 14 | 19.452, 15 | ), 16 | }, 17 | "DeiT": { 18 | "deit_tiny_patch16_224": "https://tfhub.dev/sayakpaul/deit_tiny_patch16_224/1", 19 | "deit_tiny_distilled_patch16_224": "https://tfhub.dev/sayakpaul/deit_tiny_distilled_patch16_224/1", 20 | "deit_small_patch16_224": "https://tfhub.dev/sayakpaul/deit_small_patch16_224/1", 21 | "deit_small_distilled_patch16_224": "https://tfhub.dev/sayakpaul/deit_small_distilled_patch16_224/1", 22 | "deit_base_patch16_224": "https://tfhub.dev/sayakpaul/deit_base_patch16_224/1", 23 | "deit_base_distilled_patch16_224": "https://tfhub.dev/sayakpaul/deit_base_distilled_patch16_224/1", 24 | "deit_base_patch16_384": "https://tfhub.dev/sayakpaul/deit_base_patch16_384/1", 25 | "deit_base_distilled_patch16_384": "https://tfhub.dev/sayakpaul/deit_base_distilled_patch16_384/1", 26 | }, 27 | "Swin": { 28 | "swin_tiny_patch4_window7_224": "https://tfhub.dev/sayakpaul/swin_tiny_patch4_window7_224/1", 29 | "swin_small_patch4_window7_224": "https://tfhub.dev/sayakpaul/swin_small_patch4_window7_224/1", 30 | "swin_base_patch4_window7_224": "https://tfhub.dev/sayakpaul/swin_base_patch4_window7_224/1", 31 | "swin_base_patch4_window12_384": "https://tfhub.dev/sayakpaul/swin_base_patch4_window12_384/1", 32 | "swin_large_patch4_window7_224": "https://tfhub.dev/sayakpaul/swin_large_patch4_window7_224/1", 33 | "swin_large_patch4_window7_384": "https://tfhub.dev/sayakpaul/swin_large_patch4_window7_384/1", 34 | "swin_s3_tiny_224": "https://tfhub.dev/sayakpaul/swin_s3_tiny_224/1", 35 | "swin_s3_small_224": "https://tfhub.dev/sayakpaul/swin_s3_small_224/1", 36 | "swin_s3_base_224": "https://tfhub.dev/sayakpaul/swin_s3_base_224/1", 37 | }, 38 | "MLP-Mixer": { 39 | "mixer_b16": ( 40 | "https://tfhub.dev/sayakpaul/mixer_b16_sam_classification/1", 41 | 12.621, 42 | ), 43 | "mixer_b32": ( 44 | "https://tfhub.dev/sayakpaul/mixer_b32_sam_classification/1", 45 | 3.242, 46 | ), 47 | "mixer_l16": ( 48 | "https://tfhub.dev/sayakpaul/mixer_l16_i1k_classification/1", 49 | 44.597, 50 | ), 51 | }, 52 | } 53 | -------------------------------------------------------------------------------- /hub/run_all_benchmarks.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | 3 | from model_mapping import MODEL_NAME_MAPPING 4 | 5 | 6 | def main(): 7 | for model_family in MODEL_NAME_MAPPING: 8 | for variant in MODEL_NAME_MAPPING[model_family]: 9 | run_command_no_xla = f"python run_benchmark.py --model_family {model_family} --model_variant {variant} --log_wandb" 10 | run_command_xla = f"python run_benchmark.py --model_family {model_family} --model_variant {variant} --xla --log_wandb" 11 | for command in [run_command_no_xla, run_command_xla]: 12 | _ = subprocess.run(command.split()) 13 | 14 | 15 | if __name__ == "__main__": 16 | main() 17 | -------------------------------------------------------------------------------- /hub/run_benchmark.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | 3 | tf.keras.backend.clear_session() 4 | 5 | import argparse 6 | import sys 7 | import time 8 | 9 | from model_mapping import MODEL_NAME_MAPPING 10 | 11 | sys.path.append("..") 12 | from utilities import get_device_name, get_flops, get_model_from_hub 13 | 14 | BATCH_SIZE = 4 15 | WARMUP_ITERATIONS = 10 16 | NUM_ITERATIONS = 100 17 | NUM_CHANNELS = 3 18 | 19 | 20 | def parse_args(): 21 | parser = argparse.ArgumentParser() 22 | parser.add_argument( 23 | "--model_family", 24 | type=str, 25 | required=True, 26 | choices=list(MODEL_NAME_MAPPING.keys()), 27 | help="Model family the variant belongs to.", 28 | ) 29 | parser.add_argument( 30 | "--model_variant", 31 | type=str, 32 | required=True, 33 | choices=[ 34 | variant for k in MODEL_NAME_MAPPING for variant in MODEL_NAME_MAPPING[k] 35 | ], 36 | help="Model variant to benchmark.", 37 | ) 38 | parser.add_argument( 39 | "--resolution", 40 | type=int, 41 | default=224, 42 | help="Resolution to use for benchmarking.", 43 | ) 44 | parser.add_argument( 45 | "--xla", action="store_true", help="XLA-compile the model variants." 46 | ) 47 | parser.add_argument("--log_wandb", action="store_true", help="Log to WandB.") 48 | args = parser.parse_args() 49 | return args 50 | 51 | 52 | def main(args): 53 | if args.log_wandb: 54 | try: 55 | import wandb 56 | except Exception: 57 | raise ImportError("wandb is not installed.") 58 | 59 | # Retrieve the current model variant. 60 | print(f"Running benchmark for {args.model_variant}...") 61 | all_model_variants = MODEL_NAME_MAPPING.get(args.model_family) 62 | if "deit" in args.model_variant or "swin" in args.model_variant: 63 | model_url = all_model_variants[args.model_variant] 64 | else: 65 | model_url, flops = all_model_variants[args.model_variant] 66 | 67 | # Determine the input spec with which to run the benchmark. 68 | if "deit" in model_url: 69 | args.resolution = int(model_url.split("/")[-2].split("_")[-1]) 70 | assert args.resolution is not None 71 | if args.resolution is not None: 72 | input_spec_shape = [BATCH_SIZE] + [args.resolution, args.resolution, 3] 73 | 74 | # Initialize the model. 75 | model = get_model_from_hub(model_url, args.resolution) 76 | assert isinstance(model, tf.keras.Model) 77 | 78 | # XLA compilation. 79 | print(f"Compiling with XLA: {args.xla}...") 80 | if args.xla: 81 | model_xla = tf.function(model, jit_compile=True) 82 | 83 | # Determine the variable with which the benchmark is to be performed. 84 | benchmark_var = model_xla if args.xla else model 85 | 86 | # Generate a batch of random inputs and warm the model up. 87 | print("Warming up the model...") 88 | random_inputs = tf.random.normal(input_spec_shape) 89 | for _ in range(WARMUP_ITERATIONS): 90 | _ = benchmark_var(random_inputs, training=False) 91 | 92 | # Calculate throughput. 93 | print("Calculating throughput...") 94 | start_time = time.time() 95 | for _ in range(NUM_ITERATIONS): 96 | _ = benchmark_var(random_inputs, training=False) 97 | end_time = time.time() 98 | total_time = end_time - start_time 99 | throughput = NUM_ITERATIONS * BATCH_SIZE / total_time 100 | print("Throughput: {:.2f} samples per second".format(throughput)) 101 | 102 | # Calculate FLOPs and number of parameters. 103 | num_params = model.count_params() / 1e6 104 | if "deit" in args.model_variant or "swin" in args.model_variant: 105 | flops = (get_flops(model, input_spec_shape)[0] / 1e9) / BATCH_SIZE 106 | print(f"Model parameters (million): {num_params:.2f}") 107 | print(f"FLOPs (giga): {flops:.2f}") 108 | 109 | # Log to WandB if specified. 110 | if args.log_wandb: 111 | device_name = get_device_name() 112 | run_name = f"{args.model_variant}@xla-{args.xla}@res-{args.resolution}@device-{device_name}" 113 | wandb.init(project="keras-xla-benchmarks", name=run_name, config=args) 114 | wandb.config.update( 115 | { 116 | "family": args.model_family, 117 | "variant": args.model_variant, 118 | "resolution": args.resolution, 119 | } 120 | ) 121 | wandb.log( 122 | { 123 | "Throughput (samples/sec)": float(f"{throughput:.2f}"), 124 | "Num parameters (million)": float(f"{num_params:.2f}"), 125 | "FLOPs (giga)": float(f"{flops:.2f}"), 126 | } 127 | ) 128 | wandb.finish() 129 | 130 | 131 | if __name__ == "__main__": 132 | args = parse_args() 133 | main(args) 134 | -------------------------------------------------------------------------------- /keras_cv/README.md: -------------------------------------------------------------------------------- 1 | ## Running the benchmarks 2 | 3 | We leverage KerasCV to benchmark the following models: 4 | 5 | * [YOLOV8](https://arxiv.org/abs/2305.09972) 6 | * [RetinaNet](https://arxiv.org/abs/1708.02002) 7 | 8 | You can launch benchmarks in bulk by running `python run_all_benchmarks.py`. To run 9 | a benchmark individually, run `python run_benchmark.py`. If you do `python run_benchmark.py -h`, you will be able to see the CLI arguments supported by the script. -------------------------------------------------------------------------------- /keras_cv/analysis.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "id": "d3a5f6c5", 7 | "metadata": {}, 8 | "outputs": [], 9 | "source": [ 10 | "# Install wandb by `pip install wandb`. \n", 11 | "# And then run `!wandb login`.\n", 12 | "import wandb\n", 13 | "\n", 14 | "api = wandb.Api()\n", 15 | "entity, project = \"sayakpaul\", \"keras-xla-benchmarks\" \n", 16 | "runs = api.runs(entity + \"/\" + project) \n", 17 | "print(f\"Total runs: {len(runs)}\")" 18 | ] 19 | }, 20 | { 21 | "cell_type": "code", 22 | "execution_count": null, 23 | "id": "6c72ea85", 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "from model_mapping import MODEL_NAME_MAPPING\n", 28 | "\n", 29 | "all_variants = [\n", 30 | " variant for k in MODEL_NAME_MAPPING for variant in MODEL_NAME_MAPPING[k]\n", 31 | "]\n", 32 | "all_variants" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": null, 38 | "id": "23b0fe6a", 39 | "metadata": {}, 40 | "outputs": [], 41 | "source": [ 42 | "import pandas as pd\n", 43 | "\n", 44 | "resolutions = []\n", 45 | "accelerators = []\n", 46 | "\n", 47 | "model_families = []\n", 48 | "model_variants = []\n", 49 | "xla_status = []\n", 50 | "\n", 51 | "flops = []\n", 52 | "params = []\n", 53 | "throughputs = []\n", 54 | "\n", 55 | "for run in runs:\n", 56 | " if run.name != \"benchmark-summary\":\n", 57 | " run_config = run.config\n", 58 | " run_summary = run.summary._json_dict\n", 59 | "\n", 60 | " if (\n", 61 | " all_variants[0] in run_config[\"variant\"]\n", 62 | " or all_variants[1] in run_config[\"variant\"]\n", 63 | " ):\n", 64 | " model_families.append(run_config[\"family\"])\n", 65 | " model_variants.append(run_config[\"variant\"])\n", 66 | " resolutions.append(run_config[\"resolution\"])\n", 67 | " xla_status.append(run_config[\"xla\"])\n", 68 | "\n", 69 | " accelerator_name = run.name.split(\"@\")[-1].split(\"-\")[1]\n", 70 | " accelerators.append(accelerator_name)\n", 71 | "\n", 72 | " flops.append(run_summary[\"FLOPs (giga)\"])\n", 73 | " params.append(run_summary[\"Num parameters (million)\"])\n", 74 | " throughputs.append(run_summary[\"Throughput (samples/sec)\"])\n", 75 | "\n", 76 | "viz_df = pd.DataFrame(\n", 77 | " {\n", 78 | " \"model_family\": model_families,\n", 79 | " \"model_variant\": model_variants,\n", 80 | " \"resolution\": resolutions,\n", 81 | " \"xla\": xla_status,\n", 82 | " \"accelerator\": accelerators,\n", 83 | " \"flop (giga)\": flops,\n", 84 | " \"params (million)\": params,\n", 85 | " \"throughput (samples/sec)\": throughputs,\n", 86 | " }\n", 87 | ")\n", 88 | "viz_df.head()" 89 | ] 90 | }, 91 | { 92 | "cell_type": "code", 93 | "execution_count": null, 94 | "id": "9fa3776c", 95 | "metadata": {}, 96 | "outputs": [], 97 | "source": [ 98 | "def plot_topk_per_accelerator(\n", 99 | " accelerator=\"a100\", topk=10, resolution=320, xla_status=True\n", 100 | "):\n", 101 | " filtered_df = viz_df[viz_df[\"accelerator\"] == accelerator]\n", 102 | " subset_df = filtered_df.query(f\"resolution == {resolution} and xla == {xla_status}\")\n", 103 | " topk_df = subset_df.nlargest(topk, [\"throughput (samples/sec)\"])\n", 104 | " return topk_df" 105 | ] 106 | }, 107 | { 108 | "cell_type": "code", 109 | "execution_count": null, 110 | "id": "d351a478", 111 | "metadata": {}, 112 | "outputs": [], 113 | "source": [ 114 | "# Adapted from\n", 115 | "# https://github.com/nlp-with-transformers/notebooks/blob/main/08_model-compression.ipynb\n", 116 | "\n", 117 | "import matplotlib.pyplot as plt\n", 118 | "\n", 119 | "\n", 120 | "def plot_metrics(df, savefig=False):\n", 121 | " for model_variant in df[\"model_variant\"]:\n", 122 | " filtered = df.query(f\"model_variant == '{model_variant}'\")\n", 123 | " plt.scatter(\n", 124 | " filtered[\"flop (giga)\"],\n", 125 | " filtered[\"throughput (samples/sec)\"],\n", 126 | " alpha=0.5,\n", 127 | " s=filtered[\"params (million)\"] * 5,\n", 128 | " label=model_variant,\n", 129 | " marker=\"o\",\n", 130 | " )\n", 131 | "\n", 132 | " legend = plt.legend(bbox_to_anchor=(1, 1))\n", 133 | " for handle in legend.legendHandles:\n", 134 | " handle.set_sizes([20])\n", 135 | "\n", 136 | " plt.ylabel(\"Throughput (samples/sec)\", fontsize=14)\n", 137 | " plt.xlabel(\"FLOPS (giga)\", fontsize=14)\n", 138 | "\n", 139 | " accelerator_name = df[\"accelerator\"].unique()[0]\n", 140 | " resolution = df[\"resolution\"].unique()[0]\n", 141 | " xla_status = df[\"xla\"].unique()[0]\n", 142 | " plt.title(\n", 143 | " f\"Accelerator: {accelerator_name}, Resolution: {resolution}, XLA: {xla_status}\",\n", 144 | " fontsize=14,\n", 145 | " )\n", 146 | " if not savefig:\n", 147 | " plt.show()\n", 148 | " else:\n", 149 | " plot_name = f\"{accelerator_name}_{resolution}_{xla_status}.png\"\n", 150 | " plt.savefig(plot_name, dpi=300, bbox_inches=\"tight\")" 151 | ] 152 | }, 153 | { 154 | "cell_type": "code", 155 | "execution_count": null, 156 | "id": "5c732f83", 157 | "metadata": {}, 158 | "outputs": [], 159 | "source": [ 160 | "a100_df = plot_topk_per_accelerator(\"a100\")\n", 161 | "plot_metrics(a100_df)" 162 | ] 163 | }, 164 | { 165 | "cell_type": "code", 166 | "execution_count": null, 167 | "id": "5e066ec9", 168 | "metadata": {}, 169 | "outputs": [], 170 | "source": [ 171 | "a100_res_640_df = plot_topk_per_accelerator(\"a100\", resolution=640)\n", 172 | "plot_metrics(a100_res_640_df)" 173 | ] 174 | }, 175 | { 176 | "cell_type": "code", 177 | "execution_count": null, 178 | "id": "1d0f3636", 179 | "metadata": {}, 180 | "outputs": [], 181 | "source": [ 182 | "grouped = viz_df.groupby([\"resolution\", \"accelerator\"])[\n", 183 | " \"throughput (samples/sec)\"\n", 184 | "].idxmax()\n", 185 | "result = viz_df.loc[grouped, viz_df.columns]\n", 186 | "result" 187 | ] 188 | } 189 | ], 190 | "metadata": { 191 | "kernelspec": { 192 | "display_name": "Python 3 (ipykernel)", 193 | "language": "python", 194 | "name": "python3" 195 | }, 196 | "language_info": { 197 | "codemirror_mode": { 198 | "name": "ipython", 199 | "version": 3 200 | }, 201 | "file_extension": ".py", 202 | "mimetype": "text/x-python", 203 | "name": "python", 204 | "nbconvert_exporter": "python", 205 | "pygments_lexer": "ipython3", 206 | "version": "3.8.2" 207 | } 208 | }, 209 | "nbformat": 4, 210 | "nbformat_minor": 5 211 | } 212 | -------------------------------------------------------------------------------- /keras_cv/model_mapping.py: -------------------------------------------------------------------------------- 1 | import keras_cv 2 | 3 | MODEL_NAME_MAPPING = { 4 | "YOLOV8": {"yolo_v8_m_pascalvoc": keras_cv.models.YOLOV8Detector}, 5 | "RetinaNet": { 6 | "retinanet_resnet50_pascalvoc": keras_cv.models.RetinaNet, 7 | }, 8 | } 9 | -------------------------------------------------------------------------------- /keras_cv/run_all_benchmarks.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | 3 | from model_mapping import MODEL_NAME_MAPPING 4 | 5 | 6 | def main(): 7 | for model_family in MODEL_NAME_MAPPING: 8 | for variant in MODEL_NAME_MAPPING[model_family]: 9 | for res in [320, 640]: 10 | run_command_no_xla = f"python run_benchmark.py --model_family {model_family} --model_variant {variant} --resolution {res} --log_wandb" 11 | run_command_xla = f"python run_benchmark.py --model_family {model_family} --model_variant {variant} --resolution {res} --xla --log_wandb" 12 | for command in [run_command_no_xla, run_command_xla]: 13 | _ = subprocess.run(command.split()) 14 | 15 | 16 | if __name__ == "__main__": 17 | main() 18 | -------------------------------------------------------------------------------- /keras_cv/run_benchmark.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | 3 | tf.keras.backend.clear_session() 4 | 5 | import argparse 6 | import sys 7 | import time 8 | 9 | from model_mapping import MODEL_NAME_MAPPING 10 | 11 | sys.path.append("..") 12 | from utilities import get_device_name, get_flops 13 | 14 | BATCH_SIZE = 4 15 | WARMUP_ITERATIONS = 10 16 | NUM_ITERATIONS = 100 17 | NUM_CHANNELS = 3 18 | 19 | 20 | def parse_args(): 21 | parser = argparse.ArgumentParser() 22 | parser.add_argument( 23 | "--model_family", 24 | type=str, 25 | required=True, 26 | choices=list(MODEL_NAME_MAPPING.keys()), 27 | help="Model family the variant belongs to.", 28 | ) 29 | parser.add_argument( 30 | "--model_variant", 31 | type=str, 32 | required=True, 33 | choices=[ 34 | variant for k in MODEL_NAME_MAPPING for variant in MODEL_NAME_MAPPING[k] 35 | ], 36 | help="Model variant to benchmark.", 37 | ) 38 | parser.add_argument( 39 | "--resolution", 40 | type=int, 41 | default=320, 42 | help="Resolution to use for benchmarking.", 43 | ) 44 | parser.add_argument( 45 | "--xla", action="store_true", help="XLA-compile the model variants." 46 | ) 47 | parser.add_argument("--log_wandb", action="store_true", help="Log to WandB.") 48 | args = parser.parse_args() 49 | return args 50 | 51 | 52 | def main(args): 53 | if args.log_wandb: 54 | try: 55 | import wandb 56 | except Exception: 57 | raise ImportError("wandb is not installed.") 58 | 59 | # Retrieve the current model variant. 60 | print(f"Running benchmark for {args.model_variant}...") 61 | all_model_variants = MODEL_NAME_MAPPING.get(args.model_family) 62 | model = all_model_variants[args.model_variant].from_preset( 63 | args.model_variant, bounding_box_format="xywh" 64 | ) 65 | assert isinstance(model, tf.keras.Model) 66 | 67 | # Determine the input spec with which to run the benchmark. 68 | if args.resolution is None: 69 | input_spec_shape = [BATCH_SIZE] + model.inputs[0].shape[1:] 70 | args.resolution = input_spec_shape[1] 71 | elif args.resolution is not None: 72 | input_spec_shape = [BATCH_SIZE] + [args.resolution, args.resolution, 3] 73 | elif input_spec_shape[1] is None and args.resolution is None: 74 | raise ValueError( 75 | "When model input spec is not available, you must provide `resolution`." 76 | ) 77 | 78 | # XLA compilation. 79 | print(f"Compiling with XLA: {args.xla}...") 80 | if args.xla: 81 | model_xla = tf.function(model, jit_compile=True) 82 | 83 | # Determine the variable with which the benchmark is to be performed. 84 | benchmark_var = model_xla if args.xla else model 85 | 86 | # Generate a batch of random inputs and warm the model up. 87 | print("Warming up the model...") 88 | random_inputs = tf.random.normal(input_spec_shape) 89 | for _ in range(WARMUP_ITERATIONS): 90 | _ = benchmark_var(random_inputs, training=False) 91 | 92 | # Calculate throughput. 93 | print("Calculating throughput...") 94 | start_time = time.time() 95 | for _ in range(NUM_ITERATIONS): 96 | _ = benchmark_var(random_inputs, training=False) 97 | end_time = time.time() 98 | total_time = end_time - start_time 99 | throughput = NUM_ITERATIONS * BATCH_SIZE / total_time 100 | print("Throughput: {:.2f} samples per second".format(throughput)) 101 | 102 | # Calculate FLOPs and number of parameters. 103 | num_params = model.count_params() / 1e6 104 | flops = (get_flops(model, input_spec_shape)[0] / 1e9) / BATCH_SIZE 105 | print(f"Model parameters (million): {num_params:.2f}") 106 | print(f"FLOPs (giga): {flops:.2f}") 107 | 108 | # Log to WandB if specified. 109 | if args.log_wandb: 110 | device_name = get_device_name() 111 | run_name = f"{args.model_variant}@xla-{args.xla}@res-{args.resolution}@device-{device_name}" 112 | wandb.init(project="keras-xla-benchmarks", name=run_name, config=args) 113 | wandb.config.update( 114 | { 115 | "family": args.model_family, 116 | "variant": args.model_variant, 117 | "resolution": args.resolution, 118 | } 119 | ) 120 | wandb.log( 121 | { 122 | "Throughput (samples/sec)": float(f"{throughput:.2f}"), 123 | "Num parameters (million)": float(f"{num_params:.2f}"), 124 | "FLOPs (giga)": float(f"{flops:.2f}"), 125 | } 126 | ) 127 | wandb.finish() 128 | 129 | 130 | if __name__ == "__main__": 131 | args = parse_args() 132 | main(args) 133 | -------------------------------------------------------------------------------- /keras_legacy/README.md: -------------------------------------------------------------------------------- 1 | ## Running the benchmarks 2 | 3 | We leverage `keras.applications` to benchmark the following models: 4 | 5 | * [ResNet_V1](https://arxiv.org/abs/1512.03385) 6 | * [ResNet_V2](https://arxiv.org/abs/1603.05027) 7 | * Inception ([one](http://arxiv.org/abs/1512.00567), [two](https://arxiv.org/abs/1602.07261)) 8 | * [ResNetRS](https://arxiv.org/abs/2103.07579) 9 | * [ConvNeXt](https://arxiv.org/abs/2201.03545) 10 | * [EfficientNet_V1](https://arxiv.org/abs/1905.11946) 11 | * [EfficientNet_V2](https://arxiv.org/abs/2104.00298) 12 | * [Xception](https://arxiv.org/abs/1610.02357) 13 | * [MobileNet_V1](https://arxiv.org/abs/1704.04861) 14 | * [MobileNet_V2](https://arxiv.org/abs/1801.04381) 15 | * [MobileNet_V3](https://arxiv.org/abs/1905.02244) 16 | * [VGG](https://arxiv.org/abs/1409.1556) 17 | * [RegNet_X](https://arxiv.org/abs/2003.13678) 18 | * [RegNet_Y](https://arxiv.org/abs/2003.13678) 19 | * [DenseNet](https://arxiv.org/abs/1608.06993) 20 | * [NASNet](https://arxiv.org/abs/1707.07012) 21 | 22 | You can launch benchmarks in bulk by running `python run_all_benchmarks.py`. To run 23 | a benchmark individually, run `python run_benchmark.py`. If you do `python run_benchmark.py -h`, you will be able to see the CLI arguments supported by the script. -------------------------------------------------------------------------------- /keras_legacy/analysis.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "f56ea78b", 6 | "metadata": {}, 7 | "source": [ 8 | "## Fetch the runs and collate information in a dataframe" 9 | ] 10 | }, 11 | { 12 | "cell_type": "code", 13 | "execution_count": null, 14 | "id": "a5681470", 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "# Install wandb by `pip install wandb`. \n", 19 | "# And then run `!wandb login`.\n", 20 | "import wandb\n", 21 | "\n", 22 | "api = wandb.Api()\n", 23 | "entity, project = \"sayakpaul\", \"keras-xla-benchmarks\" \n", 24 | "runs = api.runs(entity + \"/\" + project) \n", 25 | "print(f\"Total runs: {len(runs)}\")" 26 | ] 27 | }, 28 | { 29 | "cell_type": "code", 30 | "execution_count": null, 31 | "id": "5edb85ab", 32 | "metadata": {}, 33 | "outputs": [], 34 | "source": [ 35 | "from model_mapping import MODEL_NAME_MAPPING\n", 36 | "\n", 37 | "all_variants = [\n", 38 | " variant for k in MODEL_NAME_MAPPING for variant in MODEL_NAME_MAPPING[k]\n", 39 | "]" 40 | ] 41 | }, 42 | { 43 | "cell_type": "code", 44 | "execution_count": null, 45 | "id": "28f3f483", 46 | "metadata": {}, 47 | "outputs": [], 48 | "source": [ 49 | "import pandas as pd\n", 50 | "\n", 51 | "resolutions = []\n", 52 | "accelerators = []\n", 53 | "\n", 54 | "model_families = []\n", 55 | "model_variants = []\n", 56 | "xla_status = []\n", 57 | "\n", 58 | "flops = []\n", 59 | "params = []\n", 60 | "throughputs = []\n", 61 | "\n", 62 | "for run in runs:\n", 63 | " if run.name != \"benchmark-summary\":\n", 64 | " run_config = run.config\n", 65 | " run_summary = run.summary._json_dict\n", 66 | "\n", 67 | " if run_config[\"variant\"] in all_variants:\n", 68 | " model_families.append(run_config[\"family\"])\n", 69 | " model_variants.append(run_config[\"variant\"])\n", 70 | " resolutions.append(run_config[\"resolution\"])\n", 71 | " xla_status.append(run_config[\"xla\"])\n", 72 | "\n", 73 | " accelerator_name = run.name.split(\"@\")[-1].split(\"-\")[1]\n", 74 | " accelerators.append(accelerator_name)\n", 75 | "\n", 76 | " flops.append(run_summary[\"FLOPs (giga)\"])\n", 77 | " params.append(run_summary[\"Num parameters (million)\"])\n", 78 | " throughputs.append(run_summary[\"Throughput (samples/sec)\"])\n", 79 | "\n", 80 | "viz_df = pd.DataFrame(\n", 81 | " {\n", 82 | " \"model_family\": model_families,\n", 83 | " \"model_variant\": model_variants,\n", 84 | " \"resolution\": resolutions,\n", 85 | " \"xla\": xla_status,\n", 86 | " \"accelerator\": accelerators,\n", 87 | " \"flop (giga)\": flops,\n", 88 | " \"params (million)\": params,\n", 89 | " \"throughput (samples/sec)\": throughputs,\n", 90 | " }\n", 91 | ")\n", 92 | "viz_df.head()" 93 | ] 94 | }, 95 | { 96 | "cell_type": "code", 97 | "execution_count": null, 98 | "id": "7285a5ca", 99 | "metadata": {}, 100 | "outputs": [], 101 | "source": [ 102 | "viz_df[\"accelerator\"].unique()" 103 | ] 104 | }, 105 | { 106 | "cell_type": "markdown", 107 | "id": "35506bb4", 108 | "metadata": {}, 109 | "source": [ 110 | "## Filter w.r.t accelerator" 111 | ] 112 | }, 113 | { 114 | "cell_type": "code", 115 | "execution_count": null, 116 | "id": "a9cb3904", 117 | "metadata": {}, 118 | "outputs": [], 119 | "source": [ 120 | "def plot_topk_per_accelerator(\n", 121 | " accelerator=\"a100\", topk=10, resolution=224, xla_status=True\n", 122 | "):\n", 123 | " filtered_df = viz_df[viz_df[\"accelerator\"] == accelerator]\n", 124 | " subset_df = filtered_df.query(f\"resolution == {resolution} and xla == {xla_status}\")\n", 125 | " topk_df = subset_df.nlargest(topk, [\"throughput (samples/sec)\"])\n", 126 | " return topk_df" 127 | ] 128 | }, 129 | { 130 | "cell_type": "code", 131 | "execution_count": null, 132 | "id": "679cce5b", 133 | "metadata": {}, 134 | "outputs": [], 135 | "source": [ 136 | "# Adapted from\n", 137 | "# https://github.com/nlp-with-transformers/notebooks/blob/main/08_model-compression.ipynb\n", 138 | "\n", 139 | "import matplotlib.pyplot as plt\n", 140 | "\n", 141 | "\n", 142 | "def plot_metrics(df, savefig=False):\n", 143 | " for model_variant in df[\"model_variant\"]:\n", 144 | " filtered = df.query(f\"model_variant == '{model_variant}'\")\n", 145 | " plt.scatter(\n", 146 | " filtered[\"flop (giga)\"],\n", 147 | " filtered[\"throughput (samples/sec)\"],\n", 148 | " alpha=0.5,\n", 149 | " s=filtered[\"params (million)\"] * 5,\n", 150 | " label=model_variant,\n", 151 | " marker=\"o\",\n", 152 | " )\n", 153 | "\n", 154 | " legend = plt.legend(bbox_to_anchor=(1, 1))\n", 155 | " for handle in legend.legendHandles:\n", 156 | " handle.set_sizes([20])\n", 157 | "\n", 158 | " plt.ylabel(\"Throughput (samples/sec)\", fontsize=14)\n", 159 | " plt.xlabel(\"FLOPS (giga)\", fontsize=14)\n", 160 | "\n", 161 | " accelerator_name = df[\"accelerator\"].unique()[0]\n", 162 | " resolution = df[\"resolution\"].unique()[0]\n", 163 | " xla_status = df[\"xla\"].unique()[0]\n", 164 | " plt.title(\n", 165 | " f\"Accelerator: {accelerator_name}, Resolution: {resolution}, XLA: {xla_status}\",\n", 166 | " fontsize=14,\n", 167 | " )\n", 168 | " if not savefig:\n", 169 | " plt.show()\n", 170 | " else:\n", 171 | " plot_name = f\"{accelerator_name}_{resolution}_{xla_status}.png\"\n", 172 | " plt.savefig(plot_name, dpi=300, bbox_inches=\"tight\")" 173 | ] 174 | }, 175 | { 176 | "cell_type": "markdown", 177 | "id": "8ae2409f", 178 | "metadata": {}, 179 | "source": [ 180 | "### A100" 181 | ] 182 | }, 183 | { 184 | "cell_type": "code", 185 | "execution_count": null, 186 | "id": "4cb2c21e", 187 | "metadata": {}, 188 | "outputs": [], 189 | "source": [ 190 | "a100_df = plot_topk_per_accelerator(\"a100\")\n", 191 | "plot_metrics(a100_df, True)" 192 | ] 193 | }, 194 | { 195 | "cell_type": "markdown", 196 | "id": "62ba33e8", 197 | "metadata": {}, 198 | "source": [ 199 | "### V100" 200 | ] 201 | }, 202 | { 203 | "cell_type": "code", 204 | "execution_count": null, 205 | "id": "d0ac8cf8", 206 | "metadata": {}, 207 | "outputs": [], 208 | "source": [ 209 | "v100_df = plot_topk_per_accelerator(\"v100\")\n", 210 | "plot_metrics(v100_df, True)" 211 | ] 212 | }, 213 | { 214 | "cell_type": "markdown", 215 | "id": "db0495b6", 216 | "metadata": {}, 217 | "source": [ 218 | "### T4" 219 | ] 220 | }, 221 | { 222 | "cell_type": "code", 223 | "execution_count": null, 224 | "id": "45fd245f", 225 | "metadata": { 226 | "scrolled": false 227 | }, 228 | "outputs": [], 229 | "source": [ 230 | "t4_df = plot_topk_per_accelerator(\"t4\")\n", 231 | "plot_metrics(t4_df, True)" 232 | ] 233 | }, 234 | { 235 | "cell_type": "markdown", 236 | "id": "18c2f939", 237 | "metadata": {}, 238 | "source": [ 239 | "For each accelerator type, the trend of the models leading to the highest amount of throughput seem to vary a little bit. " 240 | ] 241 | }, 242 | { 243 | "cell_type": "markdown", 244 | "id": "1c832d82", 245 | "metadata": {}, 246 | "source": [ 247 | "## Resolution-wise throughput distribution" 248 | ] 249 | }, 250 | { 251 | "cell_type": "code", 252 | "execution_count": null, 253 | "id": "343d6aab", 254 | "metadata": {}, 255 | "outputs": [], 256 | "source": [ 257 | "viz_df.resolution.unique()" 258 | ] 259 | }, 260 | { 261 | "cell_type": "code", 262 | "execution_count": null, 263 | "id": "de6b8dad", 264 | "metadata": {}, 265 | "outputs": [], 266 | "source": [ 267 | "# Grouping the dataframe by unique resolutions and finding the \n", 268 | "# model variant with highest throughput per group.\n", 269 | "grouped = viz_df.groupby(\"resolution\")[\"throughput (samples/sec)\"].idxmax()\n", 270 | "\n", 271 | "# Selecting the rows with the highest throughput per group.\n", 272 | "result = viz_df.loc[grouped, viz_df.columns]\n", 273 | "result" 274 | ] 275 | }, 276 | { 277 | "cell_type": "markdown", 278 | "id": "5e882d6c", 279 | "metadata": {}, 280 | "source": [ 281 | "This means that for each resolution the highest throughput seems to have a relationship with the accelerator used for running the benchmark. \n", 282 | "\n", 283 | "What happens if we take a group by the accelerator too?" 284 | ] 285 | }, 286 | { 287 | "cell_type": "code", 288 | "execution_count": null, 289 | "id": "8e02d73a", 290 | "metadata": {}, 291 | "outputs": [], 292 | "source": [ 293 | "grouped = viz_df.groupby([\"resolution\", \"accelerator\"])[\n", 294 | " \"throughput (samples/sec)\"\n", 295 | "].idxmax()\n", 296 | "result = viz_df.loc[grouped, viz_df.columns]\n", 297 | "result" 298 | ] 299 | }, 300 | { 301 | "cell_type": "markdown", 302 | "id": "1eb14f36", 303 | "metadata": {}, 304 | "source": [ 305 | "## Highest amount of speedup from XLA grouped by model family\n", 306 | "\n", 307 | "Thanks to ChatGPT for the code used in this section." 308 | ] 309 | }, 310 | { 311 | "cell_type": "markdown", 312 | "id": "bcd031f4", 313 | "metadata": {}, 314 | "source": [ 315 | "### Absolute speedup\n", 316 | "\n", 317 | "_Which model family has the highest amount of speedup from XLA for a particular resolution (say 224) and accelerator (say A100)?_" 318 | ] 319 | }, 320 | { 321 | "cell_type": "code", 322 | "execution_count": null, 323 | "id": "fdea6091", 324 | "metadata": {}, 325 | "outputs": [], 326 | "source": [ 327 | "# Filter rows w.r.t the resolution of 224 and A100 accelerator.\n", 328 | "viz_df_224_a100 = viz_df.query(f\"resolution == 224 and accelerator == 'a100'\")\n", 329 | "\n", 330 | "# Filter rows where xla is True (XLA enabled).\n", 331 | "xla_enabled = viz_df_224_a100[viz_df_224_a100[\"xla\"]]\n", 332 | "\n", 333 | "# Filter rows where xla is False (XLA disabled).\n", 334 | "xla_disabled = viz_df_224_a100[~viz_df_224_a100[\"xla\"]]\n", 335 | "\n", 336 | "# Group by 'model_family' and calculate the speedup for each model variant.\n", 337 | "grouped = []\n", 338 | "for model_family, group in xla_enabled.groupby(\"model_family\"):\n", 339 | " for model_variant, variant_group in group.groupby(\"model_variant\"):\n", 340 | " throughput_with_xla = variant_group[\"throughput (samples/sec)\"].values[0]\n", 341 | " throughput_without_xla = xla_disabled[\n", 342 | " (xla_disabled[\"model_family\"] == model_family)\n", 343 | " & (xla_disabled[\"model_variant\"] == model_variant)\n", 344 | " ][\"throughput (samples/sec)\"].values[0]\n", 345 | " speedup = throughput_with_xla - throughput_without_xla\n", 346 | " grouped.append(\n", 347 | " {\n", 348 | " \"model_family\": model_family,\n", 349 | " \"model_variant\": model_variant,\n", 350 | " \"speedup\": speedup,\n", 351 | " }\n", 352 | " )\n", 353 | "\n", 354 | "# Create a dataframe from the grouped results.\n", 355 | "result = pd.DataFrame(grouped)\n", 356 | "\n", 357 | "# Find the model variant with the highest speedup per model family.\n", 358 | "max_speedup = result.groupby(\"model_family\")[\"speedup\"].idxmax()\n", 359 | "result_max_speedup = result.loc[max_speedup]\n", 360 | "result_max_speedup.sort_values(by=\"speedup\", ascending=False)" 361 | ] 362 | }, 363 | { 364 | "cell_type": "markdown", 365 | "id": "1c44d30b", 366 | "metadata": {}, 367 | "source": [ 368 | "### In terms of relative percentages" 369 | ] 370 | }, 371 | { 372 | "cell_type": "code", 373 | "execution_count": null, 374 | "id": "c4ee20a7", 375 | "metadata": {}, 376 | "outputs": [], 377 | "source": [ 378 | "# Filter rows where xla is True (XLA enabled).\n", 379 | "xla_enabled = viz_df_224_a100.query(\"xla == True\")\n", 380 | "\n", 381 | "# Filter rows where xla is False (XLA disabled).\n", 382 | "xla_disabled = viz_df_224_a100.query(\"xla == False\")\n", 383 | "\n", 384 | "# Group by 'model_family' and calculate the speedup for each model variant.\n", 385 | "grouped = []\n", 386 | "for model_family, group in xla_enabled.groupby(\"model_family\"):\n", 387 | " for model_variant, variant_group in group.groupby(\"model_variant\"):\n", 388 | " throughput_with_xla = variant_group[\"throughput (samples/sec)\"].values[0]\n", 389 | " throughput_without_xla = xla_disabled.query(\n", 390 | " \"model_family == @model_family and model_variant == @model_variant\"\n", 391 | " )[\"throughput (samples/sec)\"].values[0]\n", 392 | " speedup_percentage = (\n", 393 | " (throughput_with_xla - throughput_without_xla) / throughput_without_xla\n", 394 | " ) * 100\n", 395 | " grouped.append(\n", 396 | " {\n", 397 | " \"model_family\": model_family,\n", 398 | " \"model_variant\": model_variant,\n", 399 | " \"speedup_percentage\": speedup_percentage,\n", 400 | " }\n", 401 | " )\n", 402 | "\n", 403 | "# Create a dataframe from the grouped results.\n", 404 | "result = pd.DataFrame(grouped)\n", 405 | "\n", 406 | "# Find the model variant with the highest speedup percentage per model family.\n", 407 | "max_speedup = result.groupby(\"model_family\")[\"speedup_percentage\"].idxmax()\n", 408 | "result_max_speedup = result.loc[max_speedup]\n", 409 | "result_max_speedup.sort_values(by=\"speedup_percentage\", ascending=False)" 410 | ] 411 | } 412 | ], 413 | "metadata": { 414 | "kernelspec": { 415 | "display_name": "Python 3 (ipykernel)", 416 | "language": "python", 417 | "name": "python3" 418 | }, 419 | "language_info": { 420 | "codemirror_mode": { 421 | "name": "ipython", 422 | "version": 3 423 | }, 424 | "file_extension": ".py", 425 | "mimetype": "text/x-python", 426 | "name": "python", 427 | "nbconvert_exporter": "python", 428 | "pygments_lexer": "ipython3", 429 | "version": "3.8.2" 430 | } 431 | }, 432 | "nbformat": 4, 433 | "nbformat_minor": 5 434 | } 435 | -------------------------------------------------------------------------------- /keras_legacy/model_mapping.py: -------------------------------------------------------------------------------- 1 | from tensorflow import keras 2 | 3 | MODEL_NAME_MAPPING = { 4 | "ResNet_V1": { 5 | "resnet50_v1": keras.applications.ResNet50, 6 | "resnet101_v1": keras.applications.ResNet101, 7 | "resnet152_v1": keras.applications.ResNet152, 8 | }, 9 | "ResNet_V2": { 10 | "resnet50_v2": keras.applications.ResNet50V2, 11 | "resnet101_v2": keras.applications.ResNet101V2, 12 | "resnet152_v2": keras.applications.ResNet152V2, 13 | }, 14 | "Inception": { 15 | "inception_v3": keras.applications.InceptionV3, 16 | "inception_resnetv2": keras.applications.InceptionResNetV2, 17 | }, 18 | "ResNetRS": { 19 | "resnetrs_50": keras.applications.ResNetRS50, 20 | "resnetrs_101": keras.applications.ResNetRS101, 21 | "resnetrs_152": keras.applications.ResNetRS152, 22 | "resnetrs_200": keras.applications.ResNetRS200, 23 | "resnetrs_270": keras.applications.ResNetRS270, 24 | "resnetrs_350": keras.applications.ResNetRS350, 25 | "resnetrs_420": keras.applications.ResNetRS420, 26 | }, 27 | "ConvNeXt": { 28 | "convnext_tiny": keras.applications.ConvNeXtTiny, 29 | "convnext_small": keras.applications.ConvNeXtSmall, 30 | "convnext_base": keras.applications.ConvNeXtBase, 31 | "convnext_large": keras.applications.ConvNeXtLarge, 32 | "convnext_xlarge": keras.applications.ConvNeXtXLarge, 33 | }, 34 | "EfficientNet_V1": { 35 | "efficient_b0": keras.applications.EfficientNetB0, 36 | "efficient_b1": keras.applications.EfficientNetB1, 37 | "efficient_b2": keras.applications.EfficientNetB2, 38 | "efficient_b3": keras.applications.EfficientNetB3, 39 | "efficient_b4": keras.applications.EfficientNetB4, 40 | "efficient_b5": keras.applications.EfficientNetB5, 41 | "efficient_b6": keras.applications.EfficientNetB6, 42 | "efficient_b7": keras.applications.EfficientNetB7, 43 | }, 44 | "EfficientNet_V2": { 45 | "efficient_b0_v2": keras.applications.EfficientNetV2B0, 46 | "efficient_b1_v2": keras.applications.EfficientNetV2B1, 47 | "efficient_b2_v2": keras.applications.EfficientNetV2B2, 48 | "efficient_b3_v2": keras.applications.EfficientNetV2B3, 49 | "efficient_l_v2": keras.applications.EfficientNetV2L, 50 | "efficient_m_v2": keras.applications.EfficientNetV2M, 51 | "efficient_s_v2": keras.applications.EfficientNetV2S, 52 | }, 53 | "Xception": {"xception": keras.applications.Xception}, 54 | "MobileNet_V1": {"mobilenet_v1": keras.applications.MobileNet}, 55 | "MobileNet_V2": {"mobilenet_v2": keras.applications.MobileNetV2}, 56 | "MobileNet_V3": { 57 | "mobilenet_v3_small": keras.applications.MobileNetV3Small, 58 | "mobilenet_v3_large": keras.applications.MobileNetV3Large, 59 | }, 60 | "VGG": {"vgg16": keras.applications.VGG16, "vgg19": keras.applications.VGG19}, 61 | "RegNet_X": { 62 | "regnetx_002": keras.applications.RegNetX002, 63 | "regnetx_004": keras.applications.RegNetX004, 64 | "regnetx_006": keras.applications.RegNetX008, 65 | "regnetx_008": keras.applications.RegNetX016, 66 | "regnetx_016": keras.applications.RegNetX002, 67 | "regnetx_032": keras.applications.RegNetX032, 68 | "regnetx_040": keras.applications.RegNetX040, 69 | "regnetx_064": keras.applications.RegNetX064, 70 | "regnetx_080": keras.applications.RegNetX080, 71 | "regnetx_120": keras.applications.RegNetX120, 72 | "regnetx_160": keras.applications.RegNetX160, 73 | "regnetx_320": keras.applications.RegNetX320, 74 | }, 75 | "RegNet_Y": { 76 | "regnety_002": keras.applications.RegNetY002, 77 | "regnety_004": keras.applications.RegNetY004, 78 | "regnety_006": keras.applications.RegNetY008, 79 | "regnety_008": keras.applications.RegNetY016, 80 | "regnety_016": keras.applications.RegNetY002, 81 | "regnety_032": keras.applications.RegNetY032, 82 | "regnety_040": keras.applications.RegNetY040, 83 | "regnety_064": keras.applications.RegNetY064, 84 | "regnety_080": keras.applications.RegNetY080, 85 | "regnety_120": keras.applications.RegNetY120, 86 | "regnety_160": keras.applications.RegNetY160, 87 | "regnety_320": keras.applications.RegNetY320, 88 | }, 89 | "DenseNet": { 90 | "densenet_121": keras.applications.DenseNet121, 91 | "densenet_169": keras.applications.DenseNet169, 92 | "densenet_201": keras.applications.DenseNet201, 93 | }, 94 | "NASNet": { 95 | "nasnet_large": keras.applications.NASNetLarge, 96 | "nasnet_mobile": keras.applications.NASNetMobile, 97 | }, 98 | } 99 | -------------------------------------------------------------------------------- /keras_legacy/run_all_benchmarks.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | 3 | from model_mapping import MODEL_NAME_MAPPING 4 | 5 | 6 | def main(): 7 | for model_family in MODEL_NAME_MAPPING: 8 | for variant in MODEL_NAME_MAPPING[model_family]: 9 | run_command_no_xla = f"python run_benchmark.py --model_family {model_family} --model_variant {variant} --log_wandb" 10 | run_command_xla = f"python run_benchmark.py --model_family {model_family} --model_variant {variant} --xla --log_wandb" 11 | for command in [run_command_no_xla, run_command_xla]: 12 | _ = subprocess.run(command.split()) 13 | 14 | 15 | if __name__ == "__main__": 16 | main() 17 | -------------------------------------------------------------------------------- /keras_legacy/run_benchmark.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | 3 | tf.keras.backend.clear_session() 4 | 5 | import argparse 6 | import sys 7 | import time 8 | 9 | from model_mapping import MODEL_NAME_MAPPING 10 | 11 | sys.path.append("..") 12 | from utilities import get_device_name, get_flops 13 | 14 | BATCH_SIZE = 4 15 | WARMUP_ITERATIONS = 10 16 | NUM_ITERATIONS = 100 17 | NUM_CHANNELS = 3 18 | DEFAULT_RESOLUTION = 224 19 | 20 | 21 | def parse_args(): 22 | parser = argparse.ArgumentParser() 23 | parser.add_argument( 24 | "--model_family", 25 | type=str, 26 | required=True, 27 | choices=list(MODEL_NAME_MAPPING.keys()), 28 | help="Model family the variant belongs to.", 29 | ) 30 | parser.add_argument( 31 | "--model_variant", 32 | type=str, 33 | required=True, 34 | choices=[ 35 | variant for k in MODEL_NAME_MAPPING for variant in MODEL_NAME_MAPPING[k] 36 | ], 37 | help="Model variant to benchmark.", 38 | ) 39 | parser.add_argument( 40 | "--resolution", 41 | type=int, 42 | default=None, 43 | help="Resolution to use for benchmarking.", 44 | ) 45 | parser.add_argument( 46 | "--xla", action="store_true", help="XLA-compile the model variants." 47 | ) 48 | parser.add_argument("--log_wandb", action="store_true", help="Log to WandB.") 49 | args = parser.parse_args() 50 | return args 51 | 52 | 53 | def main(args): 54 | if args.log_wandb: 55 | try: 56 | import wandb 57 | except Exception: 58 | raise ImportError("wandb is not installed.") 59 | 60 | # Retrieve the current model variant. 61 | print(f"Running benchmark for {args.model_variant}...") 62 | all_model_variants = MODEL_NAME_MAPPING.get(args.model_family) 63 | model = all_model_variants[args.model_variant]() 64 | assert isinstance(model, tf.keras.Model) 65 | 66 | # Determine the input spec with which to run the benchmark. 67 | if args.resolution is None: 68 | input_spec_shape = [BATCH_SIZE] + model.inputs[0].shape[1:] 69 | if input_spec_shape[1] is None: 70 | input_spec_shape = [BATCH_SIZE] + [ 71 | DEFAULT_RESOLUTION, 72 | DEFAULT_RESOLUTION, 73 | NUM_CHANNELS, 74 | ] 75 | args.resolution = input_spec_shape[1] 76 | elif args.resolution is not None: 77 | input_spec_shape = [BATCH_SIZE] + [ 78 | args.resolution, 79 | args.resolution, 80 | NUM_CHANNELS, 81 | ] 82 | 83 | if input_spec_shape[1] is None and args.resolution is None: 84 | raise ValueError( 85 | "When model input spec is not available, you must provide `resolution`." 86 | ) 87 | 88 | # XLA compilation. 89 | print(f"Compiling with XLA: {args.xla}...") 90 | if args.xla: 91 | model_xla = tf.function(model, jit_compile=True) 92 | 93 | # Determine the variable with which the benchmark is to be performed. 94 | benchmark_var = model_xla if args.xla else model 95 | 96 | # Generate a batch of random inputs and warm the model up. 97 | print("Warming up the model...") 98 | random_inputs = tf.random.normal(input_spec_shape) 99 | for _ in range(WARMUP_ITERATIONS): 100 | _ = benchmark_var(random_inputs, training=False) 101 | 102 | # Calculate throughput. 103 | print("Calculating throughput...") 104 | start_time = time.time() 105 | for _ in range(NUM_ITERATIONS): 106 | _ = benchmark_var(random_inputs, training=False) 107 | end_time = time.time() 108 | total_time = end_time - start_time 109 | throughput = NUM_ITERATIONS * BATCH_SIZE / total_time 110 | print("Throughput: {:.2f} samples per second".format(throughput)) 111 | 112 | # Calculate FLOPs and number of parameters. 113 | num_params = model.count_params() / 1e6 114 | flops = (get_flops(model, input_spec_shape)[0] / 1e9) / BATCH_SIZE 115 | print(f"Model parameters (million): {num_params:.2f}") 116 | print(f"FLOPs (giga): {flops:.2f}") 117 | 118 | # Log to WandB if specified. 119 | if args.log_wandb: 120 | device_name = get_device_name() 121 | run_name = f"{args.model_variant}@xla-{args.xla}@res-{args.resolution}@device-{device_name}" 122 | wandb.init(project="keras-xla-benchmarks", name=run_name, config=args) 123 | wandb.config.update( 124 | { 125 | "family": args.model_family, 126 | "variant": args.model_variant, 127 | "resolution": args.resolution, 128 | } 129 | ) 130 | wandb.log( 131 | { 132 | "Throughput (samples/sec)": float(f"{throughput:.2f}"), 133 | "Num parameters (million)": float(f"{num_params:.2f}"), 134 | "FLOPs (giga)": float(f"{flops:.2f}"), 135 | } 136 | ) 137 | wandb.finish() 138 | 139 | 140 | if __name__ == "__main__": 141 | args = parse_args() 142 | main(args) 143 | -------------------------------------------------------------------------------- /utilities/__init__.py: -------------------------------------------------------------------------------- 1 | from .device import get_device_name 2 | from .flops import get_flops 3 | from .hub import get_model_from_hub 4 | -------------------------------------------------------------------------------- /utilities/device.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | 3 | 4 | def get_device_name() -> str: 5 | """Retrieves the name of the GPU device on which the benchmark is being run.""" 6 | gpu_devices = tf.config.list_physical_devices("GPU") 7 | if gpu_devices: 8 | details = tf.config.experimental.get_device_details(gpu_devices[0]) 9 | name = details["device_name"].lower() 10 | 11 | if "tesla" not in name: 12 | return name.split(" ")[1].split("-")[0] 13 | else: 14 | return name.split(" ")[1] 15 | 16 | else: 17 | raise ValueError("No GPUs found!") 18 | -------------------------------------------------------------------------------- /utilities/flops.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | from tensorflow.python.framework.convert_to_constants import \ 3 | convert_variables_to_constants_v2_as_graph 4 | 5 | 6 | def get_flops(model, input_shape=(4, 224, 224, 3)): 7 | """ 8 | Calculate FLOPS for a `tf.keras.Model`. 9 | Ignore operations used in only training mode such as Initialization. 10 | Use tf.profiler of tensorflow v1 api. 11 | 12 | Args: 13 | regnety_instance: A regnety.models.model.RegNetY instance 14 | 15 | Returns: 16 | Tuple containing total float ops and paramenters 17 | 18 | Adapted from: 19 | https://github.com/AdityaKane2001/regnety/blob/1c0e3e6978e97bd8bc1c6eb3b100c012c2fc702a/regnety/utils/model_utils.py#L8 20 | """ 21 | inputs = [tf.TensorSpec(input_shape, tf.float32)] 22 | real_model = tf.function(model).get_concrete_function(inputs) 23 | frozen_func, _ = convert_variables_to_constants_v2_as_graph(real_model) 24 | run_meta = tf.compat.v1.RunMetadata() 25 | opts = tf.compat.v1.profiler.ProfileOptionBuilder.float_operation() 26 | flops = tf.compat.v1.profiler.profile( 27 | graph=frozen_func.graph, run_meta=run_meta, cmd="scope", options=opts 28 | ) 29 | return flops.total_float_ops // 2, flops.parameters 30 | -------------------------------------------------------------------------------- /utilities/hub.py: -------------------------------------------------------------------------------- 1 | """ 2 | Utilities for handling TensorFlow Hub models. 3 | """ 4 | 5 | import tensorflow as tf 6 | import tensorflow_hub as hub 7 | 8 | 9 | def get_model_from_hub(url: str, input_resolution: int): 10 | """Initializes a tf.keras.Model from a TensorFlow Hub URL.""" 11 | if "vit" not in url and "mixer" not in url: 12 | inputs = tf.keras.Input((input_resolution, input_resolution, 3)) 13 | hub_module = hub.KerasLayer(url) 14 | if "swin" in url: 15 | outputs = hub_module(inputs) 16 | else: 17 | outputs, _ = hub_module(inputs) 18 | return tf.keras.Model(inputs, outputs) 19 | else: 20 | return tf.keras.Sequential([hub.KerasLayer(url)]) 21 | --------------------------------------------------------------------------------