Add benchmarks module with analysis, plotting, and workflow
Browse filesThis commit introduces a comprehensive benchmarking framework for evaluating performance. Key additions include the `BenchmarksAnalysis` class for data processing and visualization, `Makefile` for automated tasks, LICENSE, and README for documentation, and GitHub Actions workflow for CI benchmarks.
- .env.template +8 -0
- .github/workflows/benchmark.yml +23 -0
- .gitignore +2 -1
- LICENSE +37 -0
- Makefile +27 -0
- README.md +123 -5
- VERSION +1 -0
- __init__.py +1 -0
- main.py +27 -0
- requirements.txt +80 -0
- src/__init__.py +0 -0
- src/benchmarks_analysis.py +348 -0
- src/performance_plots.py +9 -0
- src/performance_test.py +245 -0
.env.template
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Purem Licensed Key
|
| 2 |
+
PUREM_LICENSE_KEY=purem-sandbox
|
| 3 |
+
|
| 4 |
+
# Default Python VERBOSE mode: true or yes or 1
|
| 5 |
+
PUREM_VERBOSE=template.purem.verbose
|
| 6 |
+
|
| 7 |
+
# Default Python DEBUG mode: true or yes or 1
|
| 8 |
+
DEBUG=template.debug
|
.github/workflows/benchmark.yml
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Purem Benchmarks
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches:
|
| 6 |
+
- main
|
| 7 |
+
|
| 8 |
+
jobs:
|
| 9 |
+
benchmark-macos:
|
| 10 |
+
runs-on: macos-latest
|
| 11 |
+
steps:
|
| 12 |
+
- uses: actions/checkout@v3
|
| 13 |
+
- name: Set up Python
|
| 14 |
+
uses: actions/setup-python@v4
|
| 15 |
+
with:
|
| 16 |
+
python-version: "3.11"
|
| 17 |
+
- name: Install dependencies
|
| 18 |
+
run: |
|
| 19 |
+
pip install -r requirements.txt
|
| 20 |
+
pip install pytest pytest-benchmark
|
| 21 |
+
- name: Run benchmarks
|
| 22 |
+
run: |
|
| 23 |
+
make test
|
.gitignore
CHANGED
|
@@ -181,4 +181,5 @@ cython_debug/
|
|
| 181 |
#.idea/
|
| 182 |
|
| 183 |
# PyPI configuration file
|
| 184 |
-
.pypirc
|
|
|
|
|
|
| 181 |
#.idea/
|
| 182 |
|
| 183 |
# PyPI configuration file
|
| 184 |
+
.pypirc
|
| 185 |
+
|
LICENSE
CHANGED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Business Source License 1.1
|
| 2 |
+
|
| 3 |
+
Parameters
|
| 4 |
+
Licensor: Raman Marozau, sa.marozau@gmail.com
|
| 5 |
+
Licensed Work: Purem Sandbox by Work TIF Ltd <purem-sandbox-work-tif>
|
| 6 |
+
Change Date: Never
|
| 7 |
+
Change License: Proprietary License
|
| 8 |
+
Additional Use Grant: Free for personal and non-commercial research use only.
|
| 9 |
+
|
| 10 |
+
Terms
|
| 11 |
+
The Licensed Work is provided under the Business Source License 1.1 (the "License").
|
| 12 |
+
|
| 13 |
+
The Licensor grants you a non-exclusive, worldwide, non-transferable, limited right to use, copy, distribute, and modify the Licensed Work subject to the following terms:
|
| 14 |
+
|
| 15 |
+
Commercial Use Restriction
|
| 16 |
+
You may use the Licensed Work freely for non-commercial purposes.
|
| 17 |
+
Commercial use requires a separate commercial license from the Licensor.
|
| 18 |
+
|
| 19 |
+
Availability of Source Code
|
| 20 |
+
The source code is provided under this License but may not be used for commercial purposes unless explicitly permitted.
|
| 21 |
+
|
| 22 |
+
Change Date and Transition to Open Source
|
| 23 |
+
On the Change Date, the Licensed Work will automatically transition to the Change License specified above.
|
| 24 |
+
After the Change Date, the restrictions imposed by this License no longer apply.
|
| 25 |
+
|
| 26 |
+
Additional Use Grant
|
| 27 |
+
The Licensor may grant additional permissions, such as allowing specific non-commercial uses or exceptions.
|
| 28 |
+
|
| 29 |
+
Termination
|
| 30 |
+
Any violation of these terms will result in an immediate termination of your rights under this License.
|
| 31 |
+
Upon termination, you must cease all use of the Licensed Work and delete any copies.
|
| 32 |
+
|
| 33 |
+
Disclaimer of Warranty
|
| 34 |
+
The Licensed Work is provided "AS IS", without any warranties, express or implied.
|
| 35 |
+
|
| 36 |
+
Limitation of Liability
|
| 37 |
+
The Licensor is not liable for any damages arising from the use of the Licensed Work.
|
Makefile
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
PACKAGE=purem_sandbox
|
| 2 |
+
BENCHMARKS_PLATFORM=Darwin-CPython-3.11-64bit
|
| 3 |
+
TEST=00
|
| 4 |
+
LAST_TEST_ID=00
|
| 5 |
+
|
| 6 |
+
all:
|
| 7 |
+
@echo "Nothing to do by default. Use 'make test' or 'make plot'."
|
| 8 |
+
.PHONY: all
|
| 9 |
+
|
| 10 |
+
benchmarks:
|
| 11 |
+
@timestamp=$$(date +%Y%m%d_%H%M%S) && \
|
| 12 |
+
for size in 30000 50000 100000 150000 200000 300000 500000 1000000 2000000 5000000; do \
|
| 13 |
+
echo "Running tests for size = $$size"; \
|
| 14 |
+
ARRAY_SIZE=$$size pytest src/performance_test.py --color=yes -p no:warnings --disable-warnings --benchmark-sort=max --benchmark-disable-gc --benchmark-columns=min,max,mean,stddev,ops --benchmark-min-rounds=35 --benchmark-save=$${timestamp}_$${size}; \
|
| 15 |
+
done
|
| 16 |
+
.PHONY: benchmarks
|
| 17 |
+
|
| 18 |
+
plot:
|
| 19 |
+
@LAST_TEST_ID=$$(find .benchmarks/Darwin-CPython-3.11-64bit -name '*.json' | sort | tail -n 1 | sed -E 's#.*/([0-9]+)_.*#\1#'); \
|
| 20 |
+
echo "Benchmarks with LAST_TEST_ID=$$LAST_TEST_ID are plotting..."; \
|
| 21 |
+
python -m src.performance_plots $$LAST_TEST_ID $$BENCHMARKS_PLATFORM
|
| 22 |
+
.PHONY: plot
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
test: benchmarks plot
|
| 26 |
+
echo "Purem Benchmarks successfully validated various performance."
|
| 27 |
+
.PHONY: test
|
README.md
CHANGED
|
@@ -1,5 +1,123 @@
|
|
| 1 |
-
---
|
| 2 |
-
license: other
|
| 3 |
-
license_name: busl-1.1
|
| 4 |
-
license_link: LICENSE
|
| 5 |
-
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: other
|
| 3 |
+
license_name: busl-1.1
|
| 4 |
+
license_link: LICENSE
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
# Purem Benchmarks - High-Performance Mapping Operations
|
| 8 |
+
[](https://pypi.org/project/purem/)
|
| 9 |
+
[](https://developer.apple.com/documentation/apple-silicon)
|
| 10 |
+
[](https://worktif.com/documents/terms-of-service)
|
| 11 |
+
|
| 12 |
+
**The New Standard**
|
| 13 |
+
Optimized for **x86-64**, **Intel**, and **ARM (Apple Silicon M1–M4)** servers.
|
| 14 |
+
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
## About
|
| 18 |
+
|
| 19 |
+
This repository contains **real-world benchmarks** for the Purem core technology, designed for **maximum performance testing** and **local validation**.
|
| 20 |
+
|
| 21 |
+
Purem now offers a **fully licensed and notarized sandbox binary** for **Apple Silicon M1 – M4** machines.
|
| 22 |
+
|
| 23 |
+
- **Unlimited**
|
| 24 |
+
- **Unrestricted**
|
| 25 |
+
- **No signup**
|
| 26 |
+
- **No payment**
|
| 27 |
+
- **No cloud dependencies**
|
| 28 |
+
|
| 29 |
+
You can **freely test and benchmark** Purem locally – the **same architecture**, the **same performance**, ready to run **directly on your Mac**.
|
| 30 |
+
|
| 31 |
+
---
|
| 32 |
+
|
| 33 |
+
## Key Highlights
|
| 34 |
+
|
| 35 |
+
- ⚡ **Full support for x86-64 and ARM64 (Apple M1–M4) architectures.**
|
| 36 |
+
- ⚡ **Production-grade benchmark scripts** included.
|
| 37 |
+
- ⚡ **Optimized Softmax computation** using **NumPy + Numba** (maximum CPU utilization).
|
| 38 |
+
- ⚡ **Parallelized and vectorized execution** for massive data sizes (millions to billions of elements).
|
| 39 |
+
- ⚡ **Accurate cost estimation for cloud and serverless environments** (AWS Lambda, Azure Functions, etc.).
|
| 40 |
+
- ⚡ **Focus on real hardware performance, not synthetic scores.**
|
| 41 |
+
|
| 42 |
+
---
|
| 43 |
+
|
| 44 |
+
## Getting Started
|
| 45 |
+
|
| 46 |
+
### Requirements
|
| 47 |
+
|
| 48 |
+
- Python 3.11+
|
| 49 |
+
- `purem`
|
| 50 |
+
- `numpy`
|
| 51 |
+
- `numba`
|
| 52 |
+
- `torch`
|
| 53 |
+
- `pandas`
|
| 54 |
+
- `scipy`
|
| 55 |
+
- `pytest`
|
| 56 |
+
- `matplotlib`
|
| 57 |
+
- MacBook or Mac server with Apple Silicon (M1–M4) – **or any x86-64 server** with supported Purem license.
|
| 58 |
+
|
| 59 |
+
### Installation
|
| 60 |
+
|
| 61 |
+
Clone the repository:
|
| 62 |
+
|
| 63 |
+
```bash
|
| 64 |
+
git clone https://github.com/worktif/purem_benchmarks.git
|
| 65 |
+
cd purem_benchmarks
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
Install dependencies:
|
| 69 |
+
|
| 70 |
+
```bash
|
| 71 |
+
pip install -r requirements.txt
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
### Running Benchmarks
|
| 75 |
+
|
| 76 |
+
```bash
|
| 77 |
+
make test
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
Generates full performance plots under `src/purem_benchmarks/` showing a runtime vs input size.
|
| 81 |
+
|
| 82 |
+
Check it out: [CI/CD Purem Benchmarks](https://github.com/worktif/purem_sandbox/actions)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
---
|
| 86 |
+
|
| 87 |
+
## Licensing
|
| 88 |
+
|
| 89 |
+
- **Apple Silicon (M1–M4):**
|
| 90 |
+
The sandbox binary is **permanently free to use** – no registration required.
|
| 91 |
+
You can **fully develop, benchmark, and integrate** locally.
|
| 92 |
+
|
| 93 |
+
- **x86-64 Servers (Intel/AMD):**
|
| 94 |
+
A separate licensed version is available.
|
| 95 |
+
Please refer to the [Purem by Work TIF website](https://www.worktif.com) for more details.
|
| 96 |
+
|
| 97 |
+
---
|
| 98 |
+
|
| 99 |
+
## Important Dates
|
| 100 |
+
|
| 101 |
+
- 🗓️ **Sandbox Version Public Release:**
|
| 102 |
+
**April 28th, 2025**
|
| 103 |
+
|
| 104 |
+
---
|
| 105 |
+
|
| 106 |
+
## Why Benchmark with Purem?
|
| 107 |
+
|
| 108 |
+
By using the free sandbox, you can:
|
| 109 |
+
|
| 110 |
+
- Validate performance claims **locally**.
|
| 111 |
+
- Benchmark **your own models** with production-grade accuracy.
|
| 112 |
+
- Optimize cloud costs based on **real runtime data**.
|
| 113 |
+
- Prepare real-world production integrations **with no vendor lock-in**.
|
| 114 |
+
|
| 115 |
+
---
|
| 116 |
+
|
| 117 |
+
## Contact
|
| 118 |
+
|
| 119 |
+
For more information and licensing inquiries, please visit the [Purem by Work TIF Official Website](https://www.worktif.com).
|
| 120 |
+
|
| 121 |
+
---
|
| 122 |
+
|
| 123 |
+
> **Purem – Engineering the New Standard of Performance.**
|
VERSION
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
1.3.7
|
__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
__version__ = "1.3.7"
|
main.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Business Source License 1.1
|
| 3 |
+
|
| 4 |
+
Copyright (C) 2025 Raman Marozau, raman@worktif.com
|
| 5 |
+
Use of this software is governed by the Business Source License included in the LICENSE.TXT file and at www.mariadb.com/bsl11.
|
| 6 |
+
|
| 7 |
+
Change Date: Never
|
| 8 |
+
On the date above, in accordance with the Business Source License, use of this software will be governed by the open source license specified in the LICENSE file.
|
| 9 |
+
Additional Use Grant: Free for personal and non-commercial research use only.
|
| 10 |
+
|
| 11 |
+
SPDX-License-Identifier: BUSL-1.1
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
# This is a sample Python script.
|
| 15 |
+
|
| 16 |
+
# Press ⌃R to execute it or replace it with your code.
|
| 17 |
+
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def print_hi(name):
|
| 21 |
+
# Use a breakpoint in the code line below to debug your script.
|
| 22 |
+
print(f"Hi, {name}") # Press ⌘F8 to toggle the breakpoint.
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# Press the green button in the gutter to run the script.
|
| 26 |
+
if __name__ == "__main__":
|
| 27 |
+
print_hi("PyCharm")
|
requirements.txt
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
purem==2.1.6
|
| 2 |
+
annotated-types==0.7.0
|
| 3 |
+
backports.tarfile==1.2.0
|
| 4 |
+
black==25.1.0
|
| 5 |
+
botocore==1.37.37
|
| 6 |
+
certifi==2025.1.31
|
| 7 |
+
cffi==1.17.1
|
| 8 |
+
chalice==1.31.4
|
| 9 |
+
charset-normalizer==3.4.1
|
| 10 |
+
click==8.1.8
|
| 11 |
+
contourpy==1.3.2
|
| 12 |
+
coverage==7.8.0
|
| 13 |
+
cycler==0.12.1
|
| 14 |
+
dotenv==0.9.9
|
| 15 |
+
execnet==2.1.1
|
| 16 |
+
filelock==3.17.0
|
| 17 |
+
flake8==7.2.0
|
| 18 |
+
fonttools==4.57.0
|
| 19 |
+
fsspec==2025.2.0
|
| 20 |
+
id==1.5.0
|
| 21 |
+
idna==3.10
|
| 22 |
+
iniconfig==2.0.0
|
| 23 |
+
jax==0.5.1
|
| 24 |
+
jaxlib==0.5.1
|
| 25 |
+
Jinja2==3.1.5
|
| 26 |
+
jmespath==1.0.1
|
| 27 |
+
kiwisolver==1.4.8
|
| 28 |
+
llvmlite==0.44.0
|
| 29 |
+
markdown-it-py==3.0.0
|
| 30 |
+
MarkupSafe==3.0.2
|
| 31 |
+
matplotlib==3.10.1
|
| 32 |
+
mccabe==0.7.0
|
| 33 |
+
mdurl==0.1.2
|
| 34 |
+
ml_dtypes==0.5.1
|
| 35 |
+
more-itertools==10.6.0
|
| 36 |
+
mpmath==1.3.0
|
| 37 |
+
mypy-extensions==1.0.0
|
| 38 |
+
networkx==3.4.2
|
| 39 |
+
nh3==0.2.21
|
| 40 |
+
numba==0.61.0
|
| 41 |
+
numpy==2.1.3
|
| 42 |
+
opt_einsum==3.4.0
|
| 43 |
+
packaging==24.2
|
| 44 |
+
pandas==2.2.3
|
| 45 |
+
pathspec==0.12.1
|
| 46 |
+
pillow==11.2.1
|
| 47 |
+
pluggy==1.5.0
|
| 48 |
+
py==1.11.0
|
| 49 |
+
py-cpuinfo==9.0.0
|
| 50 |
+
pycodestyle==2.13.0
|
| 51 |
+
pycparser==2.22
|
| 52 |
+
pydantic==2.10.6
|
| 53 |
+
pydantic_core==2.27.2
|
| 54 |
+
pyflakes==3.3.2
|
| 55 |
+
Pygments==2.19.1
|
| 56 |
+
pyparsing==3.2.3
|
| 57 |
+
pytest==8.3.5
|
| 58 |
+
pytest-asyncio==0.25.3
|
| 59 |
+
pytest-benchmark==5.1.0
|
| 60 |
+
pytest-forked==1.6.0
|
| 61 |
+
pytest-mock==3.14.0
|
| 62 |
+
pytest-xdist==3.6.1
|
| 63 |
+
python-dateutil==2.9.0.post0
|
| 64 |
+
python-dotenv==1.1.0
|
| 65 |
+
pytz==2025.2
|
| 66 |
+
PyYAML==6.0.2
|
| 67 |
+
rfc3986==2.0.0
|
| 68 |
+
rich==14.0.0
|
| 69 |
+
runs==1.2.2
|
| 70 |
+
scipy==1.15.2
|
| 71 |
+
six==1.17.0
|
| 72 |
+
sympy==1.13.1
|
| 73 |
+
tabulate==0.9.0
|
| 74 |
+
torch==2.6.0
|
| 75 |
+
typing_extensions==4.12.2
|
| 76 |
+
tzdata==2025.2
|
| 77 |
+
urllib3==2.3.0
|
| 78 |
+
uuid==1.30
|
| 79 |
+
wcwidth==0.2.13
|
| 80 |
+
xmod==1.8.1
|
src/__init__.py
ADDED
|
File without changes
|
src/benchmarks_analysis.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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10 |
+
import pandas as pd
|
| 11 |
+
from matplotlib import pyplot as plt
|
| 12 |
+
from pandas.core.interchange.dataframe_protocol import DataFrame
|
| 13 |
+
from scipy.signal import savgol_filter
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class BenchmarksAnalysis:
|
| 17 |
+
"""
|
| 18 |
+
Class for managing the analysis of benchmarks.
|
| 19 |
+
|
| 20 |
+
This class provides functionality to handle benchmark data including loading,
|
| 21 |
+
processing into a DataFrame, and generating various visual plots for performance
|
| 22 |
+
analysis. It ensures proper organization of benchmark files and provides specific
|
| 23 |
+
plot types to assess performance metrics and acceleration factors across a range
|
| 24 |
+
of input sizes.
|
| 25 |
+
|
| 26 |
+
:ivar benchmarks_plot_dir: Directory for storing generated benchmark plots.
|
| 27 |
+
:type benchmarks_plot_dir: pathlib.Path
|
| 28 |
+
:ivar test_number: The integer representation of the test identifier.
|
| 29 |
+
:type test_number: int
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def __init__(self, test_id: str) -> None:
|
| 33 |
+
self.benchmarks_plot_dir = self.benchmarks_setup()
|
| 34 |
+
self.test_number = int(test_id)
|
| 35 |
+
|
| 36 |
+
@staticmethod
|
| 37 |
+
def benchmarks_setup() -> Path:
|
| 38 |
+
"""
|
| 39 |
+
Creates and initializes a directory for storing benchmark plots.
|
| 40 |
+
|
| 41 |
+
This static method generates a uniquely named directory based on the current
|
| 42 |
+
date and time in the "purem_benchmarks" directory relative to the script's
|
| 43 |
+
location. If the directory does not already exist, it will be created. The
|
| 44 |
+
directory name includes a timestamp in the format "YYYY-MM-DD_HH_MM_SS__FFF".
|
| 45 |
+
|
| 46 |
+
:return: A `Path` object pointing to the created directory.
|
| 47 |
+
:rtype: Path
|
| 48 |
+
"""
|
| 49 |
+
current_time = datetime.datetime.now()
|
| 50 |
+
benchmarks_id: str = f"""purem_benchmarks_{current_time.strftime("%Y-%m-%d_%H_%M_%S__%f")[:-4]}"""
|
| 51 |
+
current_dir: str = os.path.dirname(__file__)
|
| 52 |
+
benchmarks_plot_dir: Path = Path(current_dir) / "purem_benchmarks" / benchmarks_id
|
| 53 |
+
os.makedirs(benchmarks_plot_dir, exist_ok=True)
|
| 54 |
+
|
| 55 |
+
return benchmarks_plot_dir
|
| 56 |
+
|
| 57 |
+
@staticmethod
|
| 58 |
+
def extract_size_from_filepath(filepath: str) -> int:
|
| 59 |
+
"""
|
| 60 |
+
Extract the `size` value from the given file path.
|
| 61 |
+
Assumes the size is encoded as the last part before the file extension.
|
| 62 |
+
"""
|
| 63 |
+
split_filepath = filepath.split("_")
|
| 64 |
+
return int(split_filepath[-1].split(".")[0])
|
| 65 |
+
|
| 66 |
+
def run(self) -> None:
|
| 67 |
+
"""
|
| 68 |
+
Executes the process of generating benchmarks and acceleration plots, as well as creating
|
| 69 |
+
and saving Markdown-formatted data frames. This function orchestrates the pipeline by
|
| 70 |
+
calling several helper methods to handle plotting and data frame construction.
|
| 71 |
+
|
| 72 |
+
:raises AnyRelevantError: Description of why and when it might be raised.
|
| 73 |
+
|
| 74 |
+
:return: None
|
| 75 |
+
"""
|
| 76 |
+
benchmarks_df = self.benchmarks_data_frame()
|
| 77 |
+
self.benchmarks_plot(benchmarks_df)
|
| 78 |
+
self.acceleration_plot(benchmarks_df)
|
| 79 |
+
|
| 80 |
+
markdown_df = self.markdown_data_frame()
|
| 81 |
+
self.markdown_save(markdown_df)
|
| 82 |
+
|
| 83 |
+
def load_benchmarks_files(self) -> List[str]:
|
| 84 |
+
"""
|
| 85 |
+
Loads benchmark files matching a specific test number from a designated directory.
|
| 86 |
+
The function identifies files in the benchmarks directory that match a given test number,
|
| 87 |
+
extracts a unique timestamp from the matching files, and retrieves all files that share
|
| 88 |
+
the same timestamp. This ensures that all related benchmark files for a specific test are
|
| 89 |
+
collected efficiently.
|
| 90 |
+
|
| 91 |
+
:param test_number: An integer representing the test number used to filter and locate
|
| 92 |
+
benchmark files. The test number will be zero-padded to ensure a four-digit format.
|
| 93 |
+
:return: A list of file paths for all benchmark files associated with the specified test
|
| 94 |
+
number and same timestamp.
|
| 95 |
+
:rtype: List[str]
|
| 96 |
+
:raises FileNotFoundError: If no benchmark files matching the specified test number
|
| 97 |
+
are found in the benchmarks directory.
|
| 98 |
+
"""
|
| 99 |
+
benchmarks_dir = ".benchmarks/Darwin-CPython-3.11-64bit"
|
| 100 |
+
search_pattern = str(self.test_number).zfill(4)
|
| 101 |
+
|
| 102 |
+
matched_files = [f for f in os.listdir(benchmarks_dir) if f.startswith(search_pattern) and f.endswith(".json")]
|
| 103 |
+
|
| 104 |
+
if not matched_files:
|
| 105 |
+
raise FileNotFoundError(f"No benchmark files found starting with {search_pattern} in {benchmarks_dir}")
|
| 106 |
+
|
| 107 |
+
file_stamp = matched_files[0].split("_")[2]
|
| 108 |
+
return [
|
| 109 |
+
os.path.join(benchmarks_dir, f)
|
| 110 |
+
for f in os.listdir(benchmarks_dir)
|
| 111 |
+
if f.split("_")[2] == file_stamp and f.endswith(".json")
|
| 112 |
+
]
|
| 113 |
+
|
| 114 |
+
def benchmarks_data_frame(self) -> pd.DataFrame:
|
| 115 |
+
"""
|
| 116 |
+
Generates a Pandas DataFrame containing benchmark data extracted
|
| 117 |
+
from all related files. The method processes multiple files, loads
|
| 118 |
+
their content, extracts benchmark statistics, and organizes them
|
| 119 |
+
into a structured tabular format.
|
| 120 |
+
|
| 121 |
+
:param self: The instance of the class containing this method.
|
| 122 |
+
|
| 123 |
+
:returns: A pandas DataFrame where each row represents a single
|
| 124 |
+
benchmark entry. The columns include 'size', 'func', 'min',
|
| 125 |
+
'max', 'mean', 'stddev', and 'ops', corresponding to the
|
| 126 |
+
benchmark statistics and other metadata.
|
| 127 |
+
:rtype: pd.DataFrame
|
| 128 |
+
"""
|
| 129 |
+
files = self.load_benchmarks_files()
|
| 130 |
+
|
| 131 |
+
records = []
|
| 132 |
+
|
| 133 |
+
for filepath in files:
|
| 134 |
+
with open(filepath, "r") as f:
|
| 135 |
+
data = json.load(f)
|
| 136 |
+
|
| 137 |
+
filepath_split = filepath.split("_")
|
| 138 |
+
|
| 139 |
+
for entry in data["benchmarks"]:
|
| 140 |
+
size = self.extract_size_from_filepath(filepath)
|
| 141 |
+
func = entry["params"]["func_name"]
|
| 142 |
+
stats = entry["stats"]
|
| 143 |
+
records.append({
|
| 144 |
+
"size": size,
|
| 145 |
+
"func": func,
|
| 146 |
+
"min": stats["min"],
|
| 147 |
+
"max": stats["max"],
|
| 148 |
+
"mean": stats["mean"],
|
| 149 |
+
"stddev": stats["stddev"],
|
| 150 |
+
"ops": stats["ops"]
|
| 151 |
+
})
|
| 152 |
+
|
| 153 |
+
return pd.DataFrame(records)
|
| 154 |
+
|
| 155 |
+
def benchmarks_plot(self, df: DataFrame) -> None:
|
| 156 |
+
"""
|
| 157 |
+
Generates and saves benchmarking plots for various performance metrics.
|
| 158 |
+
|
| 159 |
+
This function iterates over a defined list of metrics such as "min", "max", "mean",
|
| 160 |
+
"stddev", and "ops", and generates two types of plots for each metric:
|
| 161 |
+
one for the full range of input sizes and another for large input sizes only.
|
| 162 |
+
Each plot visualizes the relationship between input sizes and metric values for all
|
| 163 |
+
functions provided in the DataFrame. The x-axis is set to log scale for both
|
| 164 |
+
plots. The y-axis is also set to log scale for all metrics except "stddev".
|
| 165 |
+
The generated plots are saved as PNG files in a directory defined by
|
| 166 |
+
`self.benchmarks_plot_dir`.
|
| 167 |
+
|
| 168 |
+
:param df: A DataFrame containing benchmarking data. The DataFrame must have the
|
| 169 |
+
following columns:
|
| 170 |
+
- "func": Names of the functions being benchmarked.
|
| 171 |
+
- "size": Input sizes corresponding to the benchmarks.
|
| 172 |
+
- Metric columns (e.g., "min", "max", "mean", "stddev", "ops"): Values of the
|
| 173 |
+
respective performance metrics.
|
| 174 |
+
"""
|
| 175 |
+
metrics = ["min", "max", "mean", "stddev", "ops"]
|
| 176 |
+
|
| 177 |
+
for metric in metrics:
|
| 178 |
+
plt.figure(figsize=(10, 6))
|
| 179 |
+
for func_name in df["func"].unique():
|
| 180 |
+
data_by_func = df[df["func"] == func_name].sort_values("size")
|
| 181 |
+
plt.plot(data_by_func["size"], data_by_func[metric], label=func_name, marker='o')
|
| 182 |
+
plt.title(f"{metric.upper()} vs Size (Full Range)")
|
| 183 |
+
plt.xlabel("Input Size")
|
| 184 |
+
plt.ylabel(metric)
|
| 185 |
+
plt.legend()
|
| 186 |
+
plt.grid(True)
|
| 187 |
+
plt.xscale("log")
|
| 188 |
+
if metric != "stddev":
|
| 189 |
+
plt.yscale("log")
|
| 190 |
+
plt.tight_layout()
|
| 191 |
+
plt.savefig(f"{self.benchmarks_plot_dir}/benchmark_{metric}_full.png")
|
| 192 |
+
plt.close()
|
| 193 |
+
|
| 194 |
+
plt.figure(figsize=(10, 6))
|
| 195 |
+
for func_name in df["func"].unique():
|
| 196 |
+
data_by_func = df[(df["func"] == func_name) & (df["size"] > 1e5)].sort_values("size")
|
| 197 |
+
if not data_by_func.empty:
|
| 198 |
+
plt.plot(data_by_func["size"], data_by_func[metric], label=func_name, marker='o')
|
| 199 |
+
plt.title(f"{metric.upper()} vs Size (Large Inputs Only)")
|
| 200 |
+
plt.xlabel("Input Size (>1e5)")
|
| 201 |
+
plt.ylabel(metric)
|
| 202 |
+
plt.legend()
|
| 203 |
+
plt.grid(True)
|
| 204 |
+
plt.xscale("log")
|
| 205 |
+
if metric != "stddev":
|
| 206 |
+
plt.yscale("log")
|
| 207 |
+
plt.tight_layout()
|
| 208 |
+
plt.savefig(f"{self.benchmarks_plot_dir}/benchmark_{metric}_large.png")
|
| 209 |
+
plt.close()
|
| 210 |
+
|
| 211 |
+
def acceleration_plot(self, df: pd.DataFrame) -> None:
|
| 212 |
+
"""
|
| 213 |
+
Plots the acceleration of the "Purem" implementation relative to other functions/libraries
|
| 214 |
+
based on their performance for different input sizes. The plot shows acceleration as a
|
| 215 |
+
function of the input size as a logarithmic graph, detailing the relative performance
|
| 216 |
+
gain or loss.
|
| 217 |
+
|
| 218 |
+
This function is intended to visualize and compare performance metrics for computational
|
| 219 |
+
functions with respect to a "Purem" baseline. It ensures that shared input sizes
|
| 220 |
+
are used for comparison and applies smoothing (Savitzky-Golay filter) to the acceleration
|
| 221 |
+
curve for better interpretability.
|
| 222 |
+
|
| 223 |
+
:param df: A pandas DataFrame containing benchmarking results with the following
|
| 224 |
+
columns:
|
| 225 |
+
- "func": The name of the function or library being benchmarked.
|
| 226 |
+
- "size": The size of the input data for the benchmark.
|
| 227 |
+
- "ops": The respective operations per second or performance metric for each
|
| 228 |
+
function.
|
| 229 |
+
|
| 230 |
+
:return: None
|
| 231 |
+
"""
|
| 232 |
+
func_names = df["func"].unique()
|
| 233 |
+
|
| 234 |
+
assert any("Purem" in name for name in func_names), "Purem is missed!"
|
| 235 |
+
|
| 236 |
+
df_purem = df[df["func"].str.contains("Purem")].sort_values("size")
|
| 237 |
+
|
| 238 |
+
plt.figure(figsize=(14, 8))
|
| 239 |
+
|
| 240 |
+
for func_name in func_names:
|
| 241 |
+
if "Purem" in func_name:
|
| 242 |
+
continue
|
| 243 |
+
|
| 244 |
+
df_other = df[df["func"] == func_name].sort_values("size")
|
| 245 |
+
common_sizes = np.intersect1d(df_purem["size"], df_other["size"])
|
| 246 |
+
|
| 247 |
+
if len(common_sizes) == 0:
|
| 248 |
+
continue
|
| 249 |
+
|
| 250 |
+
purem_ops = df_purem[df_purem["size"].isin(common_sizes)]["ops"].values
|
| 251 |
+
other_ops = df_other[df_other["size"].isin(common_sizes)]["ops"].values
|
| 252 |
+
|
| 253 |
+
acceleration = purem_ops / other_ops
|
| 254 |
+
|
| 255 |
+
try:
|
| 256 |
+
if len(acceleration) >= 5:
|
| 257 |
+
acceleration_smooth = savgol_filter(acceleration, window_length=5, polyorder=2)
|
| 258 |
+
else:
|
| 259 |
+
acceleration_smooth = acceleration
|
| 260 |
+
except Exception as e:
|
| 261 |
+
warnings.warn(f"Smoothing skipped: {e}")
|
| 262 |
+
acceleration_smooth = acceleration
|
| 263 |
+
|
| 264 |
+
plt.plot(common_sizes, acceleration_smooth, marker='o', label=f"Purem vs {func_name}")
|
| 265 |
+
|
| 266 |
+
plt.xscale('log')
|
| 267 |
+
plt.yscale('log')
|
| 268 |
+
plt.axhline(y=1, color='black', linestyle='--', linewidth=1, label='Equal Performance (x1)')
|
| 269 |
+
plt.xlabel('Input Size', fontsize=14)
|
| 270 |
+
plt.ylabel('Acceleration (Purem / Other)', fontsize=14)
|
| 271 |
+
plt.title('Purem Acceleration Relative to Other Libraries (Production Level)', fontsize=16)
|
| 272 |
+
plt.grid(True, which="both", linestyle='--', linewidth=0.6)
|
| 273 |
+
plt.legend(fontsize=12)
|
| 274 |
+
plt.tight_layout()
|
| 275 |
+
plt.savefig(f"{self.benchmarks_plot_dir}/benchmark_acceleration_large.png")
|
| 276 |
+
plt.close()
|
| 277 |
+
|
| 278 |
+
def markdown_data_frame(self) -> pd.DataFrame:
|
| 279 |
+
"""
|
| 280 |
+
Converts benchmark data from files into a structured pandas DataFrame.
|
| 281 |
+
|
| 282 |
+
This method processes a collection of JSON files that contain benchmark
|
| 283 |
+
results. It reads the files, extracts relevant statistical information
|
| 284 |
+
about the benchmarking process, and formats this data into a structured
|
| 285 |
+
pandas DataFrame. Each record in the resultant DataFrame represents a
|
| 286 |
+
specific benchmark test and includes its relevant metadata and statistical
|
| 287 |
+
metrics.
|
| 288 |
+
|
| 289 |
+
:return:
|
| 290 |
+
A pandas DataFrame where each row corresponds to a benchmark with
|
| 291 |
+
columns that include details such as 'Elements', 'Function', 'OPS',
|
| 292 |
+
'Min Time (s)', 'Max Time (s)', 'Mean Time (s)', and 'Std Dev'.
|
| 293 |
+
:rtype:
|
| 294 |
+
pd.DataFrame
|
| 295 |
+
"""
|
| 296 |
+
files = self.load_benchmarks_files()
|
| 297 |
+
|
| 298 |
+
records_markdown = []
|
| 299 |
+
|
| 300 |
+
for filepath in files:
|
| 301 |
+
with open(filepath, "r") as f:
|
| 302 |
+
data = json.load(f)
|
| 303 |
+
|
| 304 |
+
filepath_split = filepath.split("_")
|
| 305 |
+
|
| 306 |
+
for b in data['benchmarks']:
|
| 307 |
+
size = self.extract_size_from_filepath(filepath)
|
| 308 |
+
func_name = b['params']['func_name']
|
| 309 |
+
stats = b['stats']
|
| 310 |
+
records_markdown.append({
|
| 311 |
+
"Elements": size,
|
| 312 |
+
"Function": func_name,
|
| 313 |
+
"OPS": stats["ops"],
|
| 314 |
+
"Min Time (s)": stats["min"],
|
| 315 |
+
"Max Time (s)": stats["max"],
|
| 316 |
+
"Mean Time (s)": stats["mean"],
|
| 317 |
+
"Std Dev": stats["stddev"]
|
| 318 |
+
})
|
| 319 |
+
|
| 320 |
+
return pd.DataFrame(records_markdown)
|
| 321 |
+
|
| 322 |
+
def markdown_save(self, df: pd.DataFrame) -> None:
|
| 323 |
+
"""
|
| 324 |
+
Saves a markdown file summarizing benchmark results in a human-readable format. The function processes
|
| 325 |
+
a pandas DataFrame containing benchmark data, formats specific columns for scientific notation or fixed-point
|
| 326 |
+
notation, and groups the results by the "Elements" column. Each group is written as a separate section
|
| 327 |
+
in the markdown file, where the file is saved to the benchmarks directory.
|
| 328 |
+
|
| 329 |
+
:param df: A pandas DataFrame containing benchmark results. Expected columns include "Elements",
|
| 330 |
+
"OPS", "Min Time (s)", "Max Time (s)", "Mean Time (s)", and "Std Dev".
|
| 331 |
+
:return: None
|
| 332 |
+
"""
|
| 333 |
+
df = df.sort_values(by=["Elements", "OPS"], ascending=[True, False])
|
| 334 |
+
|
| 335 |
+
df["Min Time (s)"] = df["Min Time (s)"].map(lambda x: f"{x:.2e}")
|
| 336 |
+
df["Max Time (s)"] = df["Max Time (s)"].map(lambda x: f"{x:.2e}")
|
| 337 |
+
df["Mean Time (s)"] = df["Mean Time (s)"].map(lambda x: f"{x:.2e}")
|
| 338 |
+
df["Std Dev"] = df["Std Dev"].map(lambda x: f"{x:.2e}")
|
| 339 |
+
df["OPS"] = df["OPS"].map(lambda x: f"{x:.2f}")
|
| 340 |
+
|
| 341 |
+
grouped = df.groupby('Elements')
|
| 342 |
+
|
| 343 |
+
with open(f"{self.benchmarks_plot_dir}/benchmarks_table.md", "w") as f:
|
| 344 |
+
f.write("# Benchmark Results\n\n")
|
| 345 |
+
for size, group in grouped:
|
| 346 |
+
f.write(f"### Elements: {size}\n\n")
|
| 347 |
+
f.write(group.drop(columns=["Elements"]).to_markdown(index=False))
|
| 348 |
+
f.write("\n\n")
|
src/performance_plots.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
|
| 3 |
+
from src.benchmarks_analysis import BenchmarksAnalysis
|
| 4 |
+
|
| 5 |
+
if __name__ == "__main__":
|
| 6 |
+
test_id = sys.argv[1]
|
| 7 |
+
print(f"Working with file: {test_id}")
|
| 8 |
+
|
| 9 |
+
BenchmarksAnalysis(test_id).run()
|
src/performance_test.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 7 |
+
import numpy as np
|
| 8 |
+
import pytest
|
| 9 |
+
import torch
|
| 10 |
+
from numba import njit
|
| 11 |
+
|
| 12 |
+
from purem import purem
|
| 13 |
+
|
| 14 |
+
purem.configure(license_key="purem-sandbox")
|
| 15 |
+
|
| 16 |
+
ARRAY_SIZE = int(os.environ.get("ARRAY_SIZE", 200_000))
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def generate_numbers(size, start=0.0, end=1.0) -> List[float]:
|
| 20 |
+
"""
|
| 21 |
+
Generates a list of random floating-point numbers within a specified range.
|
| 22 |
+
|
| 23 |
+
This function creates a list of random numbers based on the size specified by
|
| 24 |
+
the user. The numbers are uniformly distributed and fall within the range
|
| 25 |
+
defined by the `start` and `end` parameters. If `start` and `end` are not provided,
|
| 26 |
+
they default to 0.0 and 1.0, respectively.
|
| 27 |
+
|
| 28 |
+
:param size: The number of random numbers to generate.
|
| 29 |
+
:type size: int
|
| 30 |
+
:param start: The lower bound of the range for the random numbers. Defaults to 0.0.
|
| 31 |
+
:type start: float
|
| 32 |
+
:param end: The upper bound of the range for the random numbers. Defaults to 1.0.
|
| 33 |
+
:type end: float
|
| 34 |
+
:return: A list of random floating-point numbers within the specified range.
|
| 35 |
+
:rtype: list[float]
|
| 36 |
+
"""
|
| 37 |
+
return [random.uniform(start, end) for _ in range(size)]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@pytest.fixture(autouse=True)
|
| 41 |
+
def clean_memory() -> None:
|
| 42 |
+
"""
|
| 43 |
+
A pytest fixture to clean up memory before each test.
|
| 44 |
+
|
| 45 |
+
This fixture is automatically used for every test function due to the
|
| 46 |
+
`autouse=True` parameter. It ensures that garbage collection is triggered,
|
| 47 |
+
helping maintain a clean state in memory between test executions.
|
| 48 |
+
|
| 49 |
+
:return: None
|
| 50 |
+
"""
|
| 51 |
+
gc.collect()
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@pytest.fixture
|
| 55 |
+
def array_instance() -> np.ndarray:
|
| 56 |
+
"""
|
| 57 |
+
Creates and returns a numpy array fixture for testing.
|
| 58 |
+
|
| 59 |
+
This fixture generates a numpy array based on the provided
|
| 60 |
+
`generate_numbers` function and the defined `ARRAY_SIZE`.
|
| 61 |
+
The array elements are cast to the `float` data type.
|
| 62 |
+
|
| 63 |
+
:yield: A numpy array of floating-point numbers for testing.
|
| 64 |
+
:rtype: np.ndarray
|
| 65 |
+
"""
|
| 66 |
+
return np.array(generate_numbers(ARRAY_SIZE), dtype=float)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def softmax_purem(arr: np.ndarray) -> np.ndarray:
|
| 70 |
+
"""
|
| 71 |
+
Apply the softmax function to the input array.
|
| 72 |
+
|
| 73 |
+
The softmax function computes the probabilities for each element
|
| 74 |
+
in the input array by exponentiating them and normalizing the
|
| 75 |
+
results so that they sum to 1. It is commonly used in machine
|
| 76 |
+
learning classification problems.
|
| 77 |
+
|
| 78 |
+
:param arr: Input array for which to compute the softmax.
|
| 79 |
+
Should be a NumPy ndarray.
|
| 80 |
+
:type arr: np.ndarray
|
| 81 |
+
:return: The softmax-transformed array, where values represent
|
| 82 |
+
probabilities and sum to 1 over the input dimensions.
|
| 83 |
+
:rtype: np.ndarray
|
| 84 |
+
"""
|
| 85 |
+
return purem.softmax(arr)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def softmax_numpy(arr: np.ndarray) -> np.ndarray:
|
| 89 |
+
"""
|
| 90 |
+
Compute the softmax of a given array using numpy.
|
| 91 |
+
|
| 92 |
+
This function calculates the softmax of the input array. It stabilizes
|
| 93 |
+
the computation by subtracting the maximum value from the array to
|
| 94 |
+
prevent numerical overflow in the exponential calculation.
|
| 95 |
+
|
| 96 |
+
:param arr: Input array for which softmax needs to be calculated.
|
| 97 |
+
:type arr: np.ndarray
|
| 98 |
+
:return: The computed softmax values as an array.
|
| 99 |
+
:rtype: np.ndarray
|
| 100 |
+
"""
|
| 101 |
+
arr_max = np.max(arr)
|
| 102 |
+
shifted = arr - arr_max
|
| 103 |
+
arr_exp = np.exp(shifted)
|
| 104 |
+
return arr_exp / np.sum(arr_exp)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
# device = "mps" if torch.backends.mps.is_available() else "cpu"
|
| 108 |
+
device = "cpu"
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def softmax_torch(arr: np.ndarray) -> torch.Tensor:
|
| 112 |
+
"""
|
| 113 |
+
Applies the softmax function along the last dimension of the input array.
|
| 114 |
+
|
| 115 |
+
This function takes a NumPy array or similar Python data structure as input,
|
| 116 |
+
converts it to a PyTorch tensor, and computes the softmax values along the
|
| 117 |
+
last dimension. The input is cast to a float32 tensor for compatibility with
|
| 118 |
+
PyTorch computations. The result is returned as a PyTorch tensor.
|
| 119 |
+
|
| 120 |
+
:param arr: Input array to be converted to a PyTorch tensor and processed
|
| 121 |
+
using the softmax function. The array can be of any shape, with the
|
| 122 |
+
softmax computation applied along its last dimension.
|
| 123 |
+
:type arr: array-like
|
| 124 |
+
:return: A PyTorch tensor containing the softmax values computed from the
|
| 125 |
+
input array along its last dimension.
|
| 126 |
+
:rtype: torch.Tensor
|
| 127 |
+
"""
|
| 128 |
+
array_torch = torch.asarray(arr, dtype=torch.float32, device=device)
|
| 129 |
+
arr_torch = array_torch.to(dtype=torch.float32)
|
| 130 |
+
return arr_torch.softmax(dim=-1)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@njit(parallel=True, fastmath=True)
|
| 134 |
+
def softmax_numba(arr: np.ndarray) -> np.ndarray:
|
| 135 |
+
"""
|
| 136 |
+
Computes the softmax function for a given array with NumPy and Numba for
|
| 137 |
+
parallelized execution. The function calculates the exponential normalization
|
| 138 |
+
of a NumPy array to transform input values into probabilities that sum to one.
|
| 139 |
+
|
| 140 |
+
The function optimizes the computation using the maximum value of the input
|
| 141 |
+
array to improve numerical stability, specifically by avoiding overflow
|
| 142 |
+
and underflow during exponentiation.
|
| 143 |
+
|
| 144 |
+
:param arr: Input array of floats
|
| 145 |
+
:type arr: numpy.ndarray
|
| 146 |
+
:return: Array of softmax probabilities corresponding to the input
|
| 147 |
+
:rtype: numpy.ndarray
|
| 148 |
+
"""
|
| 149 |
+
n = arr.shape[0]
|
| 150 |
+
out = np.empty_like(arr)
|
| 151 |
+
x_max = -np.inf
|
| 152 |
+
for i in range(n):
|
| 153 |
+
if arr[i] > x_max:
|
| 154 |
+
x_max = arr[i]
|
| 155 |
+
total = 0.0
|
| 156 |
+
for i in range(n):
|
| 157 |
+
out[i] = math.exp(arr[i] - x_max)
|
| 158 |
+
total += out[i]
|
| 159 |
+
for i in range(n):
|
| 160 |
+
out[i] /= total
|
| 161 |
+
return out
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
functions = {
|
| 165 |
+
'Softmax: Purem': softmax_purem,
|
| 166 |
+
'Softmax: NumPy': softmax_numpy,
|
| 167 |
+
'Softmax: PyTorch': softmax_torch,
|
| 168 |
+
'Softmax: Numba': softmax_numba,
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
@pytest.mark.parametrize("func_name", [pytest.param("Softmax: Purem")])
|
| 173 |
+
def test_purem_softmax(benchmark, func_name, array_instance):
|
| 174 |
+
"""
|
| 175 |
+
Tests the performance of the `softmax_purem` function using the Benchmark fixture.
|
| 176 |
+
|
| 177 |
+
:param benchmark: Benchmark fixture provided by pytest-benchmark for measuring
|
| 178 |
+
the performance of the `softmax_purem` function.
|
| 179 |
+
:param func_name: Name of the function being tested in the benchmarking process.
|
| 180 |
+
:param array_instance: Input data instance provided to the `softmax_purem` function
|
| 181 |
+
during the benchmarking test.
|
| 182 |
+
:return: None
|
| 183 |
+
"""
|
| 184 |
+
benchmark(softmax_purem, array_instance)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
@pytest.mark.parametrize("func_name", [pytest.param("Softmax: NumPy")])
|
| 188 |
+
def test_numpy_softmax(benchmark, func_name, array_instance):
|
| 189 |
+
"""
|
| 190 |
+
Benchmark test for the numpy implementation of the softmax function. This test
|
| 191 |
+
uses pytest parametrize to evaluate the performance of the function across
|
| 192 |
+
different sizes of input and under a specific function name label. It clears
|
| 193 |
+
garbage, generates random floating-point numbers of the specified size, and
|
| 194 |
+
then benchmarks the softmax function.
|
| 195 |
+
|
| 196 |
+
:param benchmark: The pytest-benchmark fixture used for executing the
|
| 197 |
+
performance test of the softmax function.
|
| 198 |
+
:param func_name: Determines the function name label for benchmarking.
|
| 199 |
+
:param size: The size of the input data array to be generated and used in
|
| 200 |
+
the softmax function.
|
| 201 |
+
:return: None
|
| 202 |
+
"""
|
| 203 |
+
benchmark(softmax_numpy, array_instance)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
@pytest.mark.parametrize("func_name", [pytest.param("Softmax: PyTorch")])
|
| 207 |
+
def test_torch_softmax(benchmark, func_name, array_instance):
|
| 208 |
+
"""
|
| 209 |
+
Tests the performance of the PyTorch implementation of the softmax function over
|
| 210 |
+
an array of a specified size using the pytest benchmarking framework.
|
| 211 |
+
|
| 212 |
+
This test generates a random array of numbers of the given size, applies the
|
| 213 |
+
softmax operation implemented in PyTorch, and records its performance metrics
|
| 214 |
+
using the pytest-benchmark plugin.
|
| 215 |
+
|
| 216 |
+
:param benchmark: A pytest-benchmark function used to measure the performance
|
| 217 |
+
of the specified function under test.
|
| 218 |
+
:param func_name: The name of the function being tested.
|
| 219 |
+
:param size: The size of the input array for which softmax computation is executed.
|
| 220 |
+
:rtype: None
|
| 221 |
+
:return: Returns None as this function is a test case invoked by pytest.
|
| 222 |
+
"""
|
| 223 |
+
benchmark(softmax_torch, array_instance)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
@pytest.mark.parametrize("func_name", [pytest.param("Softmax: Numba")])
|
| 227 |
+
def test_numba_softmax(benchmark, func_name, array_instance):
|
| 228 |
+
"""
|
| 229 |
+
Tests the performance of the Numba-accelerated softmax function using pytest.
|
| 230 |
+
|
| 231 |
+
This test leverages the pytest benchmarking tool to measure the time taken
|
| 232 |
+
to compute the softmax operation on an array of specified size using the
|
| 233 |
+
Numba implementation. It uses parameterized inputs for varying
|
| 234 |
+
function names and sizes to validate the performance in different configurations.
|
| 235 |
+
|
| 236 |
+
:param benchmark: The pytest benchmarking fixture used to time the execution
|
| 237 |
+
of the softmax function.
|
| 238 |
+
:param func_name: The name of the function being tested. This parameter is
|
| 239 |
+
parameterized by the pytest decorator.
|
| 240 |
+
:param size: The size of the input array for which the softmax function is
|
| 241 |
+
benchmarked. This parameter is also parameterized by the
|
| 242 |
+
pytest decorator.
|
| 243 |
+
:return: None
|
| 244 |
+
"""
|
| 245 |
+
benchmark(softmax_numba, array_instance)
|