litert-precision-guard 0.1.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.
- litert_precision_guard-0.1.0/LICENSE +176 -0
- litert_precision_guard-0.1.0/PKG-INFO +243 -0
- litert_precision_guard-0.1.0/README.md +219 -0
- litert_precision_guard-0.1.0/litert_precision_guard/__init__.py +23 -0
- litert_precision_guard-0.1.0/litert_precision_guard/__main__.py +7 -0
- litert_precision_guard-0.1.0/litert_precision_guard/cli.py +105 -0
- litert_precision_guard-0.1.0/litert_precision_guard/metrics.py +85 -0
- litert_precision_guard-0.1.0/litert_precision_guard/models.py +110 -0
- litert_precision_guard-0.1.0/litert_precision_guard/report.py +119 -0
- litert_precision_guard-0.1.0/litert_precision_guard/runners.py +168 -0
- litert_precision_guard-0.1.0/litert_precision_guard/verifier.py +236 -0
- litert_precision_guard-0.1.0/litert_precision_guard.egg-info/PKG-INFO +243 -0
- litert_precision_guard-0.1.0/litert_precision_guard.egg-info/SOURCES.txt +18 -0
- litert_precision_guard-0.1.0/litert_precision_guard.egg-info/dependency_links.txt +1 -0
- litert_precision_guard-0.1.0/litert_precision_guard.egg-info/entry_points.txt +2 -0
- litert_precision_guard-0.1.0/litert_precision_guard.egg-info/requires.txt +2 -0
- litert_precision_guard-0.1.0/litert_precision_guard.egg-info/top_level.txt +1 -0
- litert_precision_guard-0.1.0/pyproject.toml +38 -0
- litert_precision_guard-0.1.0/setup.cfg +4 -0
- litert_precision_guard-0.1.0/tests/test_verifier.py +108 -0
|
@@ -0,0 +1,176 @@
|
|
|
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 exemplary 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
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: litert-precision-guard
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Automated CLI diagnostic tool to detect silent zero-vectors, NaN poisoning, and precision degradation across LiteRT hardware delegates.
|
|
5
|
+
Author: LiteRT Precision Guard Contributors
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Classifier: Development Status :: 4 - Beta
|
|
8
|
+
Classifier: Intended Audience :: Developers
|
|
9
|
+
Classifier: Intended Audience :: Science/Research
|
|
10
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
17
|
+
Classifier: Topic :: Software Development :: Testing
|
|
18
|
+
Requires-Python: >=3.9
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Requires-Dist: ai-edge-litert>=1.0.0
|
|
22
|
+
Requires-Dist: numpy>=1.22.0
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# LiteRT Precision Guard
|
|
26
|
+
|
|
27
|
+
[](https://github.com/kakasolg/litert-precision-guard/actions/workflows/test.yml)
|
|
28
|
+
[](https://opensource.org/licenses/Apache-2.0)
|
|
29
|
+
[](https://www.python.org/)
|
|
30
|
+
|
|
31
|
+
An automated diagnostic CLI tool to detect **silent numerical failures** (zero vectors, NaN/Inf poisoning, and precision underflow) when running quantized models across LiteRT hardware delegates.
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## The Problem: The Silent Failure Gap
|
|
36
|
+
|
|
37
|
+
This tool is **not** about "how to run LLMs on mobile devices"—ecosystems like Apple's [MLX](https://github.com/ml-explore/mlx-swift-examples) already run open models on Apple Silicon and iOS natively and effectively.
|
|
38
|
+
|
|
39
|
+
Instead, the problem space is specific and critical:
|
|
40
|
+
|
|
41
|
+
> **When deploying vendor-distributed, pre-quantized model files (`.tflite`) across multiple hardware backends (CPU vs. GPU delegates), there is currently no automated way to verify whether a specific delegate backend produces silently corrupted outputs without raising an explicit runtime error.**
|
|
42
|
+
|
|
43
|
+
In production edge deployments, quantized models running on GPU delegates (Metal, OpenCL, WebGPU) frequently suffer from **silent shader underflow**:
|
|
44
|
+
- The model initializes successfully without errors.
|
|
45
|
+
- Inference returns exit code `0` and non-empty output tensors.
|
|
46
|
+
- **The output values are silently all zeros (`[0.0, 0.0, ...]`), corrupted with `NaN`s, or completely degraded in semantic representation.**
|
|
47
|
+
|
|
48
|
+
### Public Precedents & Cross-Platform Empirical Evidence
|
|
49
|
+
|
|
50
|
+
This failure pattern has now been confirmed across **at least four independent environments and GPU architectures** (spanning Apple Metal, WebGPU, and physical Android devices from multiple GPU vendors), all sharing the same root cause and resolved by the same FP32 precision enforcement across three separate language bindings (Python `enforce_f32`, iOS Swift `kLiteRtDelegatePrecisionFp32`, and Android Kotlin `CompiledModel.GpuOptions.precision`):
|
|
51
|
+
|
|
52
|
+
1. **[google-ai-edge/LiteRT#7693](https://github.com/google-ai-edge/LiteRT/issues/7693)** (macOS / Metal): Quantized `EmbeddingGemma` with default GPU delegate precision outputs silent zero vectors on Metal backends, whereas enforcing FP32 precision (`enforce_f32=True`) restores correct embeddings.
|
|
53
|
+
2. **[huggingface/transformers.js#1728](https://github.com/huggingface/transformers.js/issues/1728)** (WebGPU / ONNX): WebGPU shader precision underflow on embedding/transformer layers silently collapses vector magnitudes, requiring explicit 32-bit floating point enforcement.
|
|
54
|
+
3. **Android Physical Device Empirical Validation** *(confirmed independently via the public Android LiteRT Kotlin/Java API `com.google.ai.edge.litert`, outside this tool's Python scope)*:
|
|
55
|
+
Testing pre-quantized `EmbeddingGemma` across different physical mobile SoC architectures demonstrated that two distinct GPU vendors exhibited two distinct failure modes under default precision—both completely resolved by forcing FP32 (`Precision.FP32`):
|
|
56
|
+
|
|
57
|
+
| Hardware / SoC Class | GPU Architecture | Default Precision Symptom | FP32 Enforced Result | Latency Impact (vs. CPU) |
|
|
58
|
+
| :--- | :--- | :--- | :--- | :--- |
|
|
59
|
+
| Tensor G5-based device | PowerVR | **Output norm `0.0000`** (Silent zero vector) | Norm `1.0000`, Cosine `0.999100` (Healthy) | **0.56x** *(slower than CPU)* |
|
|
60
|
+
| Snapdragon 8+ Gen 1 device | Adreno 730 | **Output norm `NaN`** (Numerical instability) | Norm `1.0000`, Cosine `0.999100` (Healthy) | **1.53x** *(faster than CPU)* |
|
|
61
|
+
|
|
62
|
+
> **Note on Performance Trade-offs**: The empirical data reveals that GPU FP32 latency is **divergent across GPU vendors**. While forcing FP32 on PowerVR resulted in 0.56x speed relative to CPU, Adreno 730 achieved 1.53x speedup over CPU. Hence, "GPU FP32 is too slow" is not a universal truth, but rather hardware- and shader-unit-dependent.
|
|
63
|
+
|
|
64
|
+
`litert-precision-guard` automates this verification on host/CI machines as a reproducible diagnostic tool and gatekeeper.
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## How It Works
|
|
69
|
+
|
|
70
|
+
```
|
|
71
|
+
┌───────────────────────────────┐
|
|
72
|
+
│ Input Model (.tflite) │
|
|
73
|
+
└──────────────┬────────────────┘
|
|
74
|
+
│
|
|
75
|
+
Generate Deterministic Inputs
|
|
76
|
+
│
|
|
77
|
+
┌─────────────────────────────┼─────────────────────────────┐
|
|
78
|
+
▼ ▼ ▼
|
|
79
|
+
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
|
80
|
+
│ CPU Baseline │ │ GPU Default │ │ GPU FP32 Enforced│
|
|
81
|
+
│ (XNNPACK) │ │ (FP16 / Mixed) │ │ (enforce_f32) │
|
|
82
|
+
└────────┬────────┘ └────────┬────────┘ └────────┬────────┘
|
|
83
|
+
│ │ │
|
|
84
|
+
│ (Ref Output) │ (Target Output) │ (Target Output)
|
|
85
|
+
└──────────────┬──────────────┴──────────────┬──────────────┘
|
|
86
|
+
▼ ▼
|
|
87
|
+
[Metrics Check] [Metrics Check]
|
|
88
|
+
- Cosine Sim vs Baseline - Cosine Sim vs Baseline
|
|
89
|
+
- Silent Zero Check - Silent Zero Check
|
|
90
|
+
- NaN / Inf Check - NaN / Inf Check
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
1. **Deterministic Probing**: Inspects model input signatures and generates type-safe synthetic inputs (token IDs for integers, normalized distributions for floats).
|
|
94
|
+
2. **Differential Comparison**: Runs the CPU reference engine (XNNPACK) to establish ground truth, then executes target delegate configurations (`gpu`, `gpu-fp32`).
|
|
95
|
+
3. **Automated Anomaly Detection**:
|
|
96
|
+
- `SILENT_ZERO_VECTOR`: Flags outputs with vanishing L2 norm ($\|\mathbf{y}\| < 10^{-4}$) where CPU baseline is healthy.
|
|
97
|
+
- `NUMERICAL_INSTABILITY`: Flags `NaN` or `Inf` values.
|
|
98
|
+
- `PRECISION_DEGRADATION`: Flags cosine similarity drop below threshold (e.g. $< 0.99$).
|
|
99
|
+
4. **CI/CD Exit Code**: Returns `0` if all evaluated backends pass, `1` if any silent failure is detected.
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
## Installation
|
|
104
|
+
|
|
105
|
+
`litert-precision-guard` maintains a minimal dependency footprint (`ai-edge-litert` and `numpy`):
|
|
106
|
+
|
|
107
|
+
```bash
|
|
108
|
+
pip install ai-edge-litert numpy
|
|
109
|
+
pip install -e .
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
---
|
|
113
|
+
|
|
114
|
+
## Usage
|
|
115
|
+
|
|
116
|
+
### Quick Start
|
|
117
|
+
|
|
118
|
+
Run verification against CPU, default GPU delegate, and FP32-enforced GPU delegate:
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
litert-precision-guard path/to/model.tflite
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
### Example Output
|
|
125
|
+
|
|
126
|
+
Evaluating `EmbeddingGemma-300M` (`embeddinggemma-300M_seq256_mixed-precision.tflite`):
|
|
127
|
+
|
|
128
|
+
```text
|
|
129
|
+
=======================================================================
|
|
130
|
+
LiteRT Delegate Precision Guard (Differential Verifier)
|
|
131
|
+
=======================================================================
|
|
132
|
+
|
|
133
|
+
Model Path: embeddinggemma-300M_seq256_mixed-precision.tflite
|
|
134
|
+
Signature: embed_256
|
|
135
|
+
Inputs: {'text_batch': [1, 256]}
|
|
136
|
+
Thresholds: Min Cosine Sim = 0.9900, Min Norm = 0.0001
|
|
137
|
+
|
|
138
|
+
Backend | Status | Cosine Sim | Norm (Ref/Tgt) | Max Diff | Diagnostics
|
|
139
|
+
-------------------------+----------+-------------+--------------------+------------+---------------------
|
|
140
|
+
cpu | PASS | 1.000000 | 1.00 / 1.00 | 0.000000 | OK (68.4 ms)
|
|
141
|
+
gpu (default / FP16) | FAIL | 0.000000 | 1.00 / 0.00 | 0.175859 | SILENT_ZERO_VECTOR
|
|
142
|
+
gpu (FP32 enforced) | PASS | 0.992228 | 1.00 / 1.00 | 0.015013 | OK (25.9 ms)
|
|
143
|
+
|
|
144
|
+
-----------------------------------------------------------------------
|
|
145
|
+
|
|
146
|
+
[DIAGNOSTIC FINDING]
|
|
147
|
+
* Detected SILENT ZERO-VECTOR / VANISHING OUTPUT on default GPU delegate.
|
|
148
|
+
* Root cause pattern: Shader precision underflow during quantized tensor computation.
|
|
149
|
+
* Known public precedent: google-ai-edge/LiteRT#7693 & huggingface/transformers.js#1728
|
|
150
|
+
* Remediation verified: Forcing FP32 on GPU delegate restored healthy cosine similarity (PASS).
|
|
151
|
+
|
|
152
|
+
>>> VERIFICATION FAILED: Silent errors or precision regressions detected. <<<
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
### CLI Options
|
|
156
|
+
|
|
157
|
+
| Flag | Type | Default | Description |
|
|
158
|
+
| :--- | :--- | :--- | :--- |
|
|
159
|
+
| `model_path` | `str` | *required* | Path to `.tflite` model file |
|
|
160
|
+
| `--backends` | `str` | `cpu,gpu,gpu-fp32` | Comma-separated backends to evaluate |
|
|
161
|
+
| `--min-cosine-similarity` | `float` | `0.99` | Cosine similarity threshold vs CPU |
|
|
162
|
+
| `--min-norm` | `float` | `1e-4` | L2 norm threshold for zero vector detection |
|
|
163
|
+
| `--seed` | `int` | `42` | Random seed for deterministic inputs |
|
|
164
|
+
| `--signature` | `str` | `None` | Specific signature key to execute |
|
|
165
|
+
| `--json-output` | `str` | `None` | Export structured JSON report |
|
|
166
|
+
| `-v`, `--verbose` | `flag` | `False` | Detailed tensor-level output |
|
|
167
|
+
|
|
168
|
+
### CI / CD Integration (GitHub Actions)
|
|
169
|
+
|
|
170
|
+
Use `litert-precision-guard` as a gatekeeper in your model build / release pipelines:
|
|
171
|
+
|
|
172
|
+
```yaml
|
|
173
|
+
name: Model Precision Verification Gate
|
|
174
|
+
|
|
175
|
+
on: [push, pull_request]
|
|
176
|
+
|
|
177
|
+
jobs:
|
|
178
|
+
verify-model-precision:
|
|
179
|
+
runs-on: macos-latest
|
|
180
|
+
steps:
|
|
181
|
+
- uses: actions/checkout@v4
|
|
182
|
+
|
|
183
|
+
- name: Set up Python
|
|
184
|
+
uses: actions/setup-python@v5
|
|
185
|
+
with:
|
|
186
|
+
python-version: '3.11'
|
|
187
|
+
|
|
188
|
+
- name: Install dependencies
|
|
189
|
+
run: |
|
|
190
|
+
pip install ai-edge-litert numpy
|
|
191
|
+
pip install .
|
|
192
|
+
|
|
193
|
+
- name: Run Precision Guard
|
|
194
|
+
run: |
|
|
195
|
+
# Fails pipeline if model produces silent zero-vectors or degraded embeddings
|
|
196
|
+
litert-precision-guard models/embedding.tflite \
|
|
197
|
+
--backends cpu,gpu-fp32 \
|
|
198
|
+
--min-cosine-similarity 0.99 \
|
|
199
|
+
--json-output artifacts/precision-report.json
|
|
200
|
+
|
|
201
|
+
- name: Upload Report Artifact
|
|
202
|
+
if: always()
|
|
203
|
+
uses: actions/upload-artifact@v4
|
|
204
|
+
with:
|
|
205
|
+
name: precision-report
|
|
206
|
+
path: artifacts/precision-report.json
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
---
|
|
210
|
+
|
|
211
|
+
## Python API Usage
|
|
212
|
+
|
|
213
|
+
You can also use the verifier programmatically within Python test suites:
|
|
214
|
+
|
|
215
|
+
```python
|
|
216
|
+
from litert_precision_guard import PrecisionVerifier
|
|
217
|
+
|
|
218
|
+
verifier = PrecisionVerifier(
|
|
219
|
+
model_path="path/to/model.tflite",
|
|
220
|
+
min_cosine_similarity=0.99,
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
report = verifier.verify()
|
|
224
|
+
|
|
225
|
+
if not report.all_passed:
|
|
226
|
+
for name, backend_report in report.backend_reports.items():
|
|
227
|
+
if not backend_report.passed:
|
|
228
|
+
print(f"Backend {name} failed: {backend_report.failure_reasons}")
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
---
|
|
232
|
+
|
|
233
|
+
## Future Roadmap
|
|
234
|
+
|
|
235
|
+
- **Multi-Runtime Extensibility**: Pluggable runner architecture for ExecuTorch (`.pte`), ONNX Runtime (CUDA / DirectML / WebGPU), and CoreML.
|
|
236
|
+
- **Dynamic Layer-by-Layer Probing**: Isolate the exact operator / sub-graph where numerical precision degrades to zero.
|
|
237
|
+
- **Automated Calibration Profile Suggestion**: Recommend per-operator FP32 fallback lists in `.tflite` quantization recipes.
|
|
238
|
+
|
|
239
|
+
---
|
|
240
|
+
|
|
241
|
+
## License
|
|
242
|
+
|
|
243
|
+
Apache License 2.0. See [LICENSE](LICENSE) for details.
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
# LiteRT Precision Guard
|
|
2
|
+
|
|
3
|
+
[](https://github.com/kakasolg/litert-precision-guard/actions/workflows/test.yml)
|
|
4
|
+
[](https://opensource.org/licenses/Apache-2.0)
|
|
5
|
+
[](https://www.python.org/)
|
|
6
|
+
|
|
7
|
+
An automated diagnostic CLI tool to detect **silent numerical failures** (zero vectors, NaN/Inf poisoning, and precision underflow) when running quantized models across LiteRT hardware delegates.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## The Problem: The Silent Failure Gap
|
|
12
|
+
|
|
13
|
+
This tool is **not** about "how to run LLMs on mobile devices"—ecosystems like Apple's [MLX](https://github.com/ml-explore/mlx-swift-examples) already run open models on Apple Silicon and iOS natively and effectively.
|
|
14
|
+
|
|
15
|
+
Instead, the problem space is specific and critical:
|
|
16
|
+
|
|
17
|
+
> **When deploying vendor-distributed, pre-quantized model files (`.tflite`) across multiple hardware backends (CPU vs. GPU delegates), there is currently no automated way to verify whether a specific delegate backend produces silently corrupted outputs without raising an explicit runtime error.**
|
|
18
|
+
|
|
19
|
+
In production edge deployments, quantized models running on GPU delegates (Metal, OpenCL, WebGPU) frequently suffer from **silent shader underflow**:
|
|
20
|
+
- The model initializes successfully without errors.
|
|
21
|
+
- Inference returns exit code `0` and non-empty output tensors.
|
|
22
|
+
- **The output values are silently all zeros (`[0.0, 0.0, ...]`), corrupted with `NaN`s, or completely degraded in semantic representation.**
|
|
23
|
+
|
|
24
|
+
### Public Precedents & Cross-Platform Empirical Evidence
|
|
25
|
+
|
|
26
|
+
This failure pattern has now been confirmed across **at least four independent environments and GPU architectures** (spanning Apple Metal, WebGPU, and physical Android devices from multiple GPU vendors), all sharing the same root cause and resolved by the same FP32 precision enforcement across three separate language bindings (Python `enforce_f32`, iOS Swift `kLiteRtDelegatePrecisionFp32`, and Android Kotlin `CompiledModel.GpuOptions.precision`):
|
|
27
|
+
|
|
28
|
+
1. **[google-ai-edge/LiteRT#7693](https://github.com/google-ai-edge/LiteRT/issues/7693)** (macOS / Metal): Quantized `EmbeddingGemma` with default GPU delegate precision outputs silent zero vectors on Metal backends, whereas enforcing FP32 precision (`enforce_f32=True`) restores correct embeddings.
|
|
29
|
+
2. **[huggingface/transformers.js#1728](https://github.com/huggingface/transformers.js/issues/1728)** (WebGPU / ONNX): WebGPU shader precision underflow on embedding/transformer layers silently collapses vector magnitudes, requiring explicit 32-bit floating point enforcement.
|
|
30
|
+
3. **Android Physical Device Empirical Validation** *(confirmed independently via the public Android LiteRT Kotlin/Java API `com.google.ai.edge.litert`, outside this tool's Python scope)*:
|
|
31
|
+
Testing pre-quantized `EmbeddingGemma` across different physical mobile SoC architectures demonstrated that two distinct GPU vendors exhibited two distinct failure modes under default precision—both completely resolved by forcing FP32 (`Precision.FP32`):
|
|
32
|
+
|
|
33
|
+
| Hardware / SoC Class | GPU Architecture | Default Precision Symptom | FP32 Enforced Result | Latency Impact (vs. CPU) |
|
|
34
|
+
| :--- | :--- | :--- | :--- | :--- |
|
|
35
|
+
| Tensor G5-based device | PowerVR | **Output norm `0.0000`** (Silent zero vector) | Norm `1.0000`, Cosine `0.999100` (Healthy) | **0.56x** *(slower than CPU)* |
|
|
36
|
+
| Snapdragon 8+ Gen 1 device | Adreno 730 | **Output norm `NaN`** (Numerical instability) | Norm `1.0000`, Cosine `0.999100` (Healthy) | **1.53x** *(faster than CPU)* |
|
|
37
|
+
|
|
38
|
+
> **Note on Performance Trade-offs**: The empirical data reveals that GPU FP32 latency is **divergent across GPU vendors**. While forcing FP32 on PowerVR resulted in 0.56x speed relative to CPU, Adreno 730 achieved 1.53x speedup over CPU. Hence, "GPU FP32 is too slow" is not a universal truth, but rather hardware- and shader-unit-dependent.
|
|
39
|
+
|
|
40
|
+
`litert-precision-guard` automates this verification on host/CI machines as a reproducible diagnostic tool and gatekeeper.
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## How It Works
|
|
45
|
+
|
|
46
|
+
```
|
|
47
|
+
┌───────────────────────────────┐
|
|
48
|
+
│ Input Model (.tflite) │
|
|
49
|
+
└──────────────┬────────────────┘
|
|
50
|
+
│
|
|
51
|
+
Generate Deterministic Inputs
|
|
52
|
+
│
|
|
53
|
+
┌─────────────────────────────┼─────────────────────────────┐
|
|
54
|
+
▼ ▼ ▼
|
|
55
|
+
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
|
56
|
+
│ CPU Baseline │ │ GPU Default │ │ GPU FP32 Enforced│
|
|
57
|
+
│ (XNNPACK) │ │ (FP16 / Mixed) │ │ (enforce_f32) │
|
|
58
|
+
└────────┬────────┘ └────────┬────────┘ └────────┬────────┘
|
|
59
|
+
│ │ │
|
|
60
|
+
│ (Ref Output) │ (Target Output) │ (Target Output)
|
|
61
|
+
└──────────────┬──────────────┴──────────────┬──────────────┘
|
|
62
|
+
▼ ▼
|
|
63
|
+
[Metrics Check] [Metrics Check]
|
|
64
|
+
- Cosine Sim vs Baseline - Cosine Sim vs Baseline
|
|
65
|
+
- Silent Zero Check - Silent Zero Check
|
|
66
|
+
- NaN / Inf Check - NaN / Inf Check
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
1. **Deterministic Probing**: Inspects model input signatures and generates type-safe synthetic inputs (token IDs for integers, normalized distributions for floats).
|
|
70
|
+
2. **Differential Comparison**: Runs the CPU reference engine (XNNPACK) to establish ground truth, then executes target delegate configurations (`gpu`, `gpu-fp32`).
|
|
71
|
+
3. **Automated Anomaly Detection**:
|
|
72
|
+
- `SILENT_ZERO_VECTOR`: Flags outputs with vanishing L2 norm ($\|\mathbf{y}\| < 10^{-4}$) where CPU baseline is healthy.
|
|
73
|
+
- `NUMERICAL_INSTABILITY`: Flags `NaN` or `Inf` values.
|
|
74
|
+
- `PRECISION_DEGRADATION`: Flags cosine similarity drop below threshold (e.g. $< 0.99$).
|
|
75
|
+
4. **CI/CD Exit Code**: Returns `0` if all evaluated backends pass, `1` if any silent failure is detected.
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
## Installation
|
|
80
|
+
|
|
81
|
+
`litert-precision-guard` maintains a minimal dependency footprint (`ai-edge-litert` and `numpy`):
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
pip install ai-edge-litert numpy
|
|
85
|
+
pip install -e .
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
## Usage
|
|
91
|
+
|
|
92
|
+
### Quick Start
|
|
93
|
+
|
|
94
|
+
Run verification against CPU, default GPU delegate, and FP32-enforced GPU delegate:
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
litert-precision-guard path/to/model.tflite
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### Example Output
|
|
101
|
+
|
|
102
|
+
Evaluating `EmbeddingGemma-300M` (`embeddinggemma-300M_seq256_mixed-precision.tflite`):
|
|
103
|
+
|
|
104
|
+
```text
|
|
105
|
+
=======================================================================
|
|
106
|
+
LiteRT Delegate Precision Guard (Differential Verifier)
|
|
107
|
+
=======================================================================
|
|
108
|
+
|
|
109
|
+
Model Path: embeddinggemma-300M_seq256_mixed-precision.tflite
|
|
110
|
+
Signature: embed_256
|
|
111
|
+
Inputs: {'text_batch': [1, 256]}
|
|
112
|
+
Thresholds: Min Cosine Sim = 0.9900, Min Norm = 0.0001
|
|
113
|
+
|
|
114
|
+
Backend | Status | Cosine Sim | Norm (Ref/Tgt) | Max Diff | Diagnostics
|
|
115
|
+
-------------------------+----------+-------------+--------------------+------------+---------------------
|
|
116
|
+
cpu | PASS | 1.000000 | 1.00 / 1.00 | 0.000000 | OK (68.4 ms)
|
|
117
|
+
gpu (default / FP16) | FAIL | 0.000000 | 1.00 / 0.00 | 0.175859 | SILENT_ZERO_VECTOR
|
|
118
|
+
gpu (FP32 enforced) | PASS | 0.992228 | 1.00 / 1.00 | 0.015013 | OK (25.9 ms)
|
|
119
|
+
|
|
120
|
+
-----------------------------------------------------------------------
|
|
121
|
+
|
|
122
|
+
[DIAGNOSTIC FINDING]
|
|
123
|
+
* Detected SILENT ZERO-VECTOR / VANISHING OUTPUT on default GPU delegate.
|
|
124
|
+
* Root cause pattern: Shader precision underflow during quantized tensor computation.
|
|
125
|
+
* Known public precedent: google-ai-edge/LiteRT#7693 & huggingface/transformers.js#1728
|
|
126
|
+
* Remediation verified: Forcing FP32 on GPU delegate restored healthy cosine similarity (PASS).
|
|
127
|
+
|
|
128
|
+
>>> VERIFICATION FAILED: Silent errors or precision regressions detected. <<<
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
### CLI Options
|
|
132
|
+
|
|
133
|
+
| Flag | Type | Default | Description |
|
|
134
|
+
| :--- | :--- | :--- | :--- |
|
|
135
|
+
| `model_path` | `str` | *required* | Path to `.tflite` model file |
|
|
136
|
+
| `--backends` | `str` | `cpu,gpu,gpu-fp32` | Comma-separated backends to evaluate |
|
|
137
|
+
| `--min-cosine-similarity` | `float` | `0.99` | Cosine similarity threshold vs CPU |
|
|
138
|
+
| `--min-norm` | `float` | `1e-4` | L2 norm threshold for zero vector detection |
|
|
139
|
+
| `--seed` | `int` | `42` | Random seed for deterministic inputs |
|
|
140
|
+
| `--signature` | `str` | `None` | Specific signature key to execute |
|
|
141
|
+
| `--json-output` | `str` | `None` | Export structured JSON report |
|
|
142
|
+
| `-v`, `--verbose` | `flag` | `False` | Detailed tensor-level output |
|
|
143
|
+
|
|
144
|
+
### CI / CD Integration (GitHub Actions)
|
|
145
|
+
|
|
146
|
+
Use `litert-precision-guard` as a gatekeeper in your model build / release pipelines:
|
|
147
|
+
|
|
148
|
+
```yaml
|
|
149
|
+
name: Model Precision Verification Gate
|
|
150
|
+
|
|
151
|
+
on: [push, pull_request]
|
|
152
|
+
|
|
153
|
+
jobs:
|
|
154
|
+
verify-model-precision:
|
|
155
|
+
runs-on: macos-latest
|
|
156
|
+
steps:
|
|
157
|
+
- uses: actions/checkout@v4
|
|
158
|
+
|
|
159
|
+
- name: Set up Python
|
|
160
|
+
uses: actions/setup-python@v5
|
|
161
|
+
with:
|
|
162
|
+
python-version: '3.11'
|
|
163
|
+
|
|
164
|
+
- name: Install dependencies
|
|
165
|
+
run: |
|
|
166
|
+
pip install ai-edge-litert numpy
|
|
167
|
+
pip install .
|
|
168
|
+
|
|
169
|
+
- name: Run Precision Guard
|
|
170
|
+
run: |
|
|
171
|
+
# Fails pipeline if model produces silent zero-vectors or degraded embeddings
|
|
172
|
+
litert-precision-guard models/embedding.tflite \
|
|
173
|
+
--backends cpu,gpu-fp32 \
|
|
174
|
+
--min-cosine-similarity 0.99 \
|
|
175
|
+
--json-output artifacts/precision-report.json
|
|
176
|
+
|
|
177
|
+
- name: Upload Report Artifact
|
|
178
|
+
if: always()
|
|
179
|
+
uses: actions/upload-artifact@v4
|
|
180
|
+
with:
|
|
181
|
+
name: precision-report
|
|
182
|
+
path: artifacts/precision-report.json
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
---
|
|
186
|
+
|
|
187
|
+
## Python API Usage
|
|
188
|
+
|
|
189
|
+
You can also use the verifier programmatically within Python test suites:
|
|
190
|
+
|
|
191
|
+
```python
|
|
192
|
+
from litert_precision_guard import PrecisionVerifier
|
|
193
|
+
|
|
194
|
+
verifier = PrecisionVerifier(
|
|
195
|
+
model_path="path/to/model.tflite",
|
|
196
|
+
min_cosine_similarity=0.99,
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
report = verifier.verify()
|
|
200
|
+
|
|
201
|
+
if not report.all_passed:
|
|
202
|
+
for name, backend_report in report.backend_reports.items():
|
|
203
|
+
if not backend_report.passed:
|
|
204
|
+
print(f"Backend {name} failed: {backend_report.failure_reasons}")
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
---
|
|
208
|
+
|
|
209
|
+
## Future Roadmap
|
|
210
|
+
|
|
211
|
+
- **Multi-Runtime Extensibility**: Pluggable runner architecture for ExecuTorch (`.pte`), ONNX Runtime (CUDA / DirectML / WebGPU), and CoreML.
|
|
212
|
+
- **Dynamic Layer-by-Layer Probing**: Isolate the exact operator / sub-graph where numerical precision degrades to zero.
|
|
213
|
+
- **Automated Calibration Profile Suggestion**: Recommend per-operator FP32 fallback lists in `.tflite` quantization recipes.
|
|
214
|
+
|
|
215
|
+
---
|
|
216
|
+
|
|
217
|
+
## License
|
|
218
|
+
|
|
219
|
+
Apache License 2.0. See [LICENSE](LICENSE) for details.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""LiteRT Precision Guard: Automated diagnostic tool for silent delegate failures."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
__author__ = "LiteRT Precision Guard Contributors"
|
|
5
|
+
__license__ = "Apache-2.0"
|
|
6
|
+
|
|
7
|
+
from litert_precision_guard.models import (
|
|
8
|
+
BackendConfig,
|
|
9
|
+
BackendReport,
|
|
10
|
+
FailureReason,
|
|
11
|
+
TensorComparison,
|
|
12
|
+
VerificationReport,
|
|
13
|
+
)
|
|
14
|
+
from litert_precision_guard.verifier import PrecisionVerifier
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"PrecisionVerifier",
|
|
18
|
+
"VerificationReport",
|
|
19
|
+
"BackendReport",
|
|
20
|
+
"BackendConfig",
|
|
21
|
+
"FailureReason",
|
|
22
|
+
"TensorComparison",
|
|
23
|
+
]
|