nn-lit 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
nn_lit-1.0.0/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025- ABrain One and contributors; PyTorch to TensorFlow Lite neural network model converter (c) 2025 Andrey Ignatov
4
+ All rights reserved.
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
nn_lit-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,386 @@
1
+ Metadata-Version: 2.4
2
+ Name: nn-lit
3
+ Version: 1.0.0
4
+ Summary: Automated PyTorch-to-Android conversion and benchmarking on physical mobile devices
5
+ Author-email: ABrain One and contributors <AI@ABrain.one>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2025- ABrain One and contributors; PyTorch to TensorFlow Lite neural network model converter (c) 2025 Andrey Ignatov
9
+ All rights reserved.
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
28
+
29
+ Project-URL: Homepage, https://ABrain.one
30
+ Project-URL: Repository, https://github.com/ABrain-One/nn-lite
31
+ Project-URL: Bug Tracker, https://github.com/ABrain-One/nn-lite/issues
32
+ Keywords: on-device inference,Android,mobile AI,benchmarking,TensorFlow Lite,LiteRT,quantization,NNAPI,PyTorch,edge AI
33
+ Classifier: Programming Language :: Python :: 3
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Operating System :: OS Independent
36
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
37
+ Classifier: Topic :: System :: Benchmark
38
+ Classifier: Intended Audience :: Developers
39
+ Classifier: Intended Audience :: Science/Research
40
+ Requires-Python: >=3.10
41
+ Description-Content-Type: text/markdown
42
+ License-File: LICENSE
43
+ Requires-Dist: litert-torch==0.8.0
44
+ Requires-Dist: ai-edge-litert==2.1.2
45
+ Requires-Dist: ai-edge-quantizer==0.4.2
46
+ Requires-Dist: ai-edge-tensorflow==2.21.0.dev20251110
47
+ Requires-Dist: torch-xla2==0.0.1.dev202412041639
48
+ Requires-Dist: torchao==0.15.0
49
+ Requires-Dist: torch==2.9.1
50
+ Requires-Dist: torchvision==0.24.1
51
+ Requires-Dist: nn-dataset<2.3,>=2.2.11
52
+ Requires-Dist: numpy==2.2.6
53
+ Requires-Dist: huggingface_hub==1.4.0
54
+ Requires-Dist: filelock>=3.12
55
+ Requires-Dist: pillow==12.1.0
56
+ Provides-Extra: emulator
57
+ Requires-Dist: nn-dataset; extra == "emulator"
58
+ Dynamic: license-file
59
+
60
+ # Mobile-Ready AI: Verification and Deployment on Edge Devices
61
+
62
+ <img src='https://abrain.one/img/nnlite-logo.png' width='25%'/>
63
+
64
+ The original open-source version of the <a href='https://github.com/ABrain-One/NN-Lite/'>NN Lite</a> was developed by <strong>Faraz Kayani</strong>, <strong>Saif U Din</strong> and <strong>Muhammad Ahsan Hussain</strong> at the Computer Vision Laboratory, University of Würzburg, Germany, under the supervision and technical guidance of <strong>Dr. Dmitry Ignatov</strong>, whose foundational work established the basis for the project.
65
+
66
+ NN-Lite measures how fast PyTorch models run on real Android phones. For every model in the
67
+ [LEMUR / NN Dataset](https://github.com/ABrain-One/nn-dataset) it:
68
+
69
+ 1. rebuilds the network and loads its trained weights,
70
+ 2. converts it to LiteRT (TensorFlow Lite) in **FP32** and full-integer **INT8** (calibrated on real
71
+ CIFAR-10 training images, prepared with the model's own input transform),
72
+ 3. copies it to a phone over USB and times it with the official `benchmark_model` tool on the **CPU**, **GPU** and **NPU (NNAPI)**,
73
+ 4. saves one JSON record per model, precision and device, in the same layout as the dataset.
74
+
75
+ Runs are unattended and resumable: NN-Lite waits if the USB cable is unplugged, lets the phone
76
+ cool down between models, restarts itself every 50 models (`--restart-every`), and records
77
+ failures instead of skipping them. An optional emulator path (Android Studio) is also included.
78
+
79
+ ## Requirements
80
+
81
+ - Linux (tested on Ubuntu) or macOS on Apple Silicon, with Python 3.10 or newer
82
+ - `adb` (Android platform tools): `sudo apt install adb` on Linux, `brew install --cask android-platform-tools`
83
+ on macOS, or the [SDK platform tools](https://developer.android.com/tools/releases/platform-tools)
84
+ - An Android phone with USB debugging enabled (see [Connect a phone](#connect-a-phone)); no root is needed
85
+ - An internet connection and about 2 GB of free disk space: the first run downloads the LEMUR
86
+ database (about 1.2 GB unpacked) and the CIFAR-10 training set used for INT8 calibration;
87
+ model weights are downloaded from Hugging Face as they are needed
88
+
89
+ ## Installation
90
+
91
+ Create and activate a virtual environment (recommended).
92
+
93
+ For Linux/Mac:
94
+ ```bash
95
+ python3 -m venv .venv
96
+ source .venv/bin/activate
97
+ python -m pip install --upgrade pip
98
+ ```
99
+ For Windows:
100
+ ```bash
101
+ python3 -m venv .venv
102
+ .venv\Scripts\activate
103
+ python -m pip install --upgrade pip
104
+ ```
105
+
106
+ Install NN-Lite from PyPI:
107
+ ```bash
108
+ pip install nn-lit
109
+ ```
110
+ This also installs the [NN Dataset](https://github.com/ABrain-One/nn-dataset) package, from
111
+ which NN-Lite reads the models, so nothing else needs to be cloned. Results are written to
112
+ `nn-lite-results/` in the folder you run NN-Lite from; see
113
+ [Contributing results to the dataset](#contributing-results-to-the-dataset) to add them to LEMUR.
114
+
115
+ Or install it from source:
116
+ ```bash
117
+ git clone https://github.com/ABrain-One/nn-lite.git
118
+ cd nn-lite
119
+ pip install -e .
120
+ ```
121
+
122
+ If `nn-lite-bench` stops with `ModuleNotFoundError: No module named 'ab.lite'`, your `PYTHONPATH`
123
+ includes a checkout of the NN Dataset, whose `ab` folder then hides the installed one
124
+ (`python -c "import ab; print(ab.__path__)"` shows which is used). Remove that folder from
125
+ `PYTHONPATH`, or run `unset PYTHONPATH`, and try again.
126
+
127
+ ### Working with an nn-dataset checkout
128
+
129
+ If you commit results to the NN Dataset, or benchmark models that are newer than the installed
130
+ package, NN-Lite can read the models from a git checkout of the dataset and write the results
131
+ straight into it. When NN-Lite is installed from source, a checkout next to it is found
132
+ automatically:
133
+ ```bash
134
+ cd ..
135
+ git clone https://github.com/ABrain-One/nn-dataset.git
136
+ ```
137
+ ```
138
+ your-folder/
139
+ ├── nn-lite/
140
+ └── nn-dataset/
141
+ ```
142
+ An `nn-dataset` checkout in the folder NN-Lite is run from is found automatically as well. A
143
+ checkout elsewhere is chosen with `--dataset-root /path/to/nn-dataset` or the `NN_DATASET_ROOT`
144
+ environment variable. NN-Lite prints at start-up where it reads the models from and where it
145
+ writes the results.
146
+
147
+ ## Connect a phone
148
+
149
+ 1. On the phone, open **Settings → About phone** and tap **Build number** seven times to enable developer options.
150
+ 2. Open **Settings → Developer options** (on some phones under **System**) and turn on **USB debugging**.
151
+ 3. Connect the phone to the computer with a USB cable and accept the **Allow USB debugging?** prompt on the phone.
152
+ 4. Check that the phone is visible:
153
+ ```bash
154
+ adb devices
155
+ ```
156
+ It should be listed with the state `device` (not `unauthorized`). With several phones
157
+ connected, see [Several phones](#several-phones).
158
+
159
+ Keep the phone charging during long runs. NN-Lite keeps the screen awake and copies the
160
+ `benchmark_model` binary to `/data/local/tmp` on the phone automatically.
161
+
162
+ ## Quick start
163
+
164
+ Benchmark a single model (a few minutes):
165
+ ```bash
166
+ nn-lite-bench --models AirNet
167
+ ```
168
+ From a source checkout, the same command is `python -m ab.lite.torch2tflite --models AirNet`.
169
+
170
+ NN-Lite converts `AirNet` to FP32 and INT8, times each file on the CPU, GPU and NPU with
171
+ 20 runs per backend, and writes (into the nn-dataset checkout instead, if one is used):
172
+ ```
173
+ nn-lite-results/ab/nn/stat/run/tflite/fp32/img-classification_cifar-10_acc_AirNet/android_<device>.json
174
+ nn-lite-results/ab/nn/stat/run/tflite/int8/img-classification_cifar-10_acc_AirNet/android_<device>.json
175
+ ```
176
+ An abridged record (latencies are in nanoseconds; `unit` is the fastest backend):
177
+ ```json
178
+ {
179
+ "model_name": "AirNet",
180
+ "device_type": "STK-L21",
181
+ "os_version": "10 | HUAWEISTK-L21",
182
+ "valid": true,
183
+ "emulator": false,
184
+ "iterations": 20,
185
+ "duration": 55200000,
186
+ "unit": "GPU",
187
+ "cpu_duration": 329480000, "cpu_min_duration": 310111000, "cpu_max_duration": 344513000, "cpu_std_dev": 9657000.0,
188
+ "gpu_duration": 55200000, "gpu_min_duration": 53553000, "gpu_max_duration": 60863000, "gpu_std_dev": 2064000.0,
189
+ "npu_duration": 364514000, "npu_min_duration": 357856000, "npu_max_duration": 371171000, "npu_std_dev": 6657000.0,
190
+ "total_ram_kb": 3775716, "free_ram_kb": 189496, "available_ram_kb": 1617764, "cached_kb": 1638264,
191
+ "in_dim_0": 1, "in_dim_1": 128, "in_dim_2": 128, "in_dim_3": 3,
192
+ "device_analytics": { "...": "CPU cores, SoC and ARM architecture of the phone" }
193
+ }
194
+ ```
195
+ If a backend fails, its error message is stored in `cpu_error`, `gpu_error` or `npu_error`; if
196
+ all three fail, the record is kept with `"valid": false`. The full output of every failure is
197
+ appended to `_work/benchmark_errors_<device>.log` in the results folder.
198
+
199
+ Benchmark every model (runs for hours; safe to stop and restart at any time):
200
+ ```bash
201
+ nn-lite-bench
202
+ ```
203
+
204
+ | Option | Meaning |
205
+ |---|---|
206
+ | `--models NAME [NAME ...]` | Only process these models |
207
+ | `--android-runs N` | Timed runs per backend (default 20) |
208
+ | `--dataset-root PATH` | Read models from this `nn-dataset` checkout and write results into it |
209
+ | `--out PATH` | Write results to this folder instead (default: the checkout, or `./nn-lite-results`) |
210
+ | `--model-path PATH [PATH ...]` | Benchmark your own models instead (see [Your own models](#your-own-models)) |
211
+ | `--serial SERIAL` | Benchmark this phone, as listed by `adb devices` (needed when several are connected) |
212
+ | `--restart-every N` | Restart the process after every N models to free memory (default 50; 0 never restarts) |
213
+ | `--force` | Forget the connected phone's progress and start from the beginning |
214
+ | `--reinstall-bench` | Copy `benchmark_model` to the phone again |
215
+
216
+ Progress is stored per phone model in `_work/processing_state_<model>.json` of the results folder; models
217
+ listed there as processed or failed are skipped when that phone model is benchmarked again,
218
+ while a phone of another model starts from the beginning. `--force` resets the progress of the
219
+ connected phone model only. Like the result files, progress is identified by the phone model, so
220
+ a second phone of the same model continues where the first one left off.
221
+
222
+ ### Several phones
223
+
224
+ Several phones can be benchmarked at the same time from one computer, each by its own run
225
+ of NN-Lite. Choose the phone of each run with `--serial` and the serial number that
226
+ `adb devices` lists for it:
227
+ ```bash
228
+ adb devices
229
+ # List of devices attached
230
+ # R58M12ABCDE device
231
+ # 2A281FDH300 device
232
+ nn-lite-bench --serial R58M12ABCDE # in one terminal
233
+ nn-lite-bench --serial 2A281FDH300 # in another terminal
234
+ ```
235
+ Without `--serial` (or the `ANDROID_SERIAL` environment variable), NN-Lite uses the only
236
+ phone connected, and stops with the list of phones if there are several. A run only ever
237
+ talks to its own phone, even if other phones are connected or reconnected during the run.
238
+
239
+ The runs can write into the same results folder: the downloads they share are made once,
240
+ and each phone has its own temporary folder. Phones of the same model share one progress
241
+ file and one result file per model, so they are benchmarked one after the other; a second
242
+ run for a phone model that is already being benchmarked stops with an error.
243
+
244
+ ## Your own models
245
+
246
+ NN-Lite also benchmarks models that are not part of the NN Dataset, without using the dataset at
247
+ all. Give the model files, or folders containing them, with `--model-path`:
248
+ ```bash
249
+ nn-lite-bench --model-path my_models/ --calib-dir sample_images/
250
+ ```
251
+ Each model is either
252
+
253
+ - a **`.pt2` file** saved with [`torch.export`](https://docs.pytorch.org/docs/stable/export.html):
254
+ it needs no Python code, and its input shape is stored in the file. Export the model in
255
+ evaluation mode (`model.eval()`), as the exported graph keeps the mode it was exported in:
256
+ ```python
257
+ torch.export.save(torch.export.export(model.eval(), (torch.randn(1, 3, 224, 224),)), "mymodel.pt2")
258
+ ```
259
+ - or a **`.py` file with a `.pt` or `.pth` file of the same name** next to it (`mymodel.py` and
260
+ `mymodel.pth`), holding either the weights (`torch.save(model.state_dict(), ...)`) or the whole
261
+ model (`torch.save(model, ...)`). NN-Lite builds the network with `create_model()` if the `.py`
262
+ file defines one, otherwise with `Net()` or the file's only model class. The input is
263
+ `--input-size` pixels square (default 224).
264
+
265
+ A `.pt` file alone is not enough: it holds the weights but not the code that defines the network,
266
+ so PyTorch cannot rebuild the model from it. Load whole-model files only from sources you trust,
267
+ as loading them can run code stored in the file.
268
+
269
+ FP32 is always benchmarked. INT8 needs sample inputs for calibration: pass a folder of images with
270
+ `--calib-dir` (up to 50 are used). They are resized to the model's input and normalised with the
271
+ ImageNet statistics, unless the `.py` file defines `input_transform`, a function that turns a PIL
272
+ image into a tensor. Results are written to `nn-lite-results/custom/{fp32,int8}/<model>/`, in the
273
+ same format as the dataset's records.
274
+
275
+ ## Contributing results to the dataset
276
+
277
+ The results folder has the same layout as the NN Dataset, so adding your measurements to LEMUR
278
+ takes three steps:
279
+ ```bash
280
+ git clone https://github.com/ABrain-One/nn-dataset.git
281
+ cp -r nn-lite-results/ab nn-dataset/
282
+ cd nn-dataset && git add ab/nn/stat/run/tflite && git commit -m "Add LiteRT benchmarks for <device>"
283
+ ```
284
+ Then open a pull request on the [NN Dataset](https://github.com/ABrain-One/nn-dataset) repository.
285
+ The `_work` folder (downloads, progress and logs) is not part of the dataset and is not copied.
286
+ From then on, NN-Lite run from the same folder finds this checkout and writes new results
287
+ straight into it.
288
+
289
+ ## Optional: emulator path (Android Studio)
290
+
291
+ The earlier version of NN-Lite runs models inside an Android emulator through the Android app in
292
+ `App/`. It uses the NN Dataset Python package installed with NN-Lite; to use its latest
293
+ development version instead:
294
+ ```bash
295
+ rm -rf db
296
+ pip uninstall -y nn-dataset
297
+ pip install --no-cache-dir git+https://github.com/ABrain-One/nn-dataset
298
+ ```
299
+
300
+ Install Android Studio 'Android Studio Narwhal 3 Feature Drop | 2025.1.3' (outside of the virtual environment) with the ready-made script (Linux):
301
+ ```bash
302
+ chmod +x install-android-studio.sh
303
+ ./install-android-studio.sh
304
+ ```
305
+
306
+ Or install it manually from the [Android Studio archive](https://developer.android.com/studio/archive):
307
+ ```bash
308
+ sudo apt update
309
+ sudo apt install openjdk-17-jdk
310
+ cd ~/Downloads
311
+ unzip android-studio-*.zip
312
+ sudo mv android-studio /opt/
313
+ /opt/android-studio/bin/studio.sh
314
+ ```
315
+ In Android Studio, select `App` and import it as a project, then go to
316
+ **Tools → Device Manager** and add a new device with the **+** symbol (e.g. Pixel 5).
317
+
318
+ Set up the Android SDK environment variables by adding these lines to the end of `~/.bashrc`,
319
+ using your own paths (shown under **Tools → Device Manager → Android SDK Location**):
320
+ ```bash
321
+ export ANDROID_SDK_ROOT="$HOME/Android/Sdk"
322
+ export ANDROID_HOME="$HOME/Android/Sdk"
323
+ export PATH="$PATH:$HOME/Android/Sdk/cmdline-tools/latest/bin:$HOME/.local/bin"
324
+ ```
325
+
326
+ Run all models, a single model, or several models:
327
+ ```bash
328
+ python -m ab.lite.torch2tflite-all
329
+ python -m ab.lite.torch2tflite-all AirNet
330
+ python -m ab.lite.torch2tflite-all AirNet ga-196 ga-197 ga-198
331
+ ```
332
+
333
+ ## Running the tests
334
+
335
+ The unit tests cover output parsing, error extraction, the result schema, the choice of the
336
+ model source and of the phone, the locks between runs and the options kept across restarts.
337
+ They need neither a phone nor PyTorch, TensorFlow or the NN Dataset:
338
+ ```bash
339
+ pip install pytest filelock
340
+ python -m pytest tests
341
+ ```
342
+
343
+ ## Contributing and support
344
+
345
+ Bug reports, questions and feature requests are welcome in the
346
+ [issue tracker](https://github.com/ABrain-One/nn-lite/issues). See [CONTRIBUTING.md](https://github.com/ABrain-One/nn-lite/blob/main/CONTRIBUTING.md)
347
+ for how to propose changes and how the project is maintained.
348
+
349
+ ## Citation
350
+
351
+ If you find this project to be useful for your research, please consider citing our articles:
352
+ ```bibtex
353
+ @article{ABrain.NN-Lite,
354
+ title = {AI on the Edge: An Automated Pipeline for PyTorch-to-Android Deployment and Benchmarking},
355
+ author = {Saif U Din and Muhammad Ahsan Hussain and Mohsin Ikram and Faraz Kayani and Dmitry Ignatov and Radu Timofte},
356
+ doi = {10.20944/preprints202511.1831.v2},
357
+ url = {https://doi.org/10.20944/preprints202511.1831.v2},
358
+ year = 2026,
359
+ month = {July},
360
+ publisher = {Preprints},
361
+ journal = {Preprints}
362
+ }
363
+
364
+ @InProceedings{ABrain.MobileDenoising,
365
+ title = {Real Image Denoising with Knowledge Distillation for High-Performance Mobile {NPUs}},
366
+ author = {Faraz Kayani and Sarmad Kayani and Asad Ahmed and Radu Timofte and Dmitry Ignatov},
367
+ booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition Workshops (CVPRW)},
368
+ pages = {3792--3800},
369
+ year={2026}
370
+ }
371
+
372
+ @InProceedings{ABrain.MobileAgeNet,
373
+ title = {{MobileAgeNet}: Lightweight Facial Age Estimation for Mobile Deployment},
374
+ author = {Arun Kumar and Aswathy Baiju and Radu Timofte and Dmitry Ignatov},
375
+ booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition Workshops (CVPRW)},
376
+ pages = {3810--3818},
377
+ year={2026}
378
+ }
379
+
380
+ ```
381
+
382
+ ## License
383
+
384
+ NN-Lite is released under the [MIT License](https://github.com/ABrain-One/nn-lite/blob/main/LICENSE).
385
+
386
+ #### The idea and leadership of Dr. Ignatov