ai-edge-litert-nightly 1.4.0.dev20250813__cp39-cp39-manylinux_2_27_aarch64.whl → 1.4.0.dev20250814__cp39-cp39-manylinux_2_27_aarch64.whl

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.

Potentially problematic release.


This version of ai-edge-litert-nightly might be problematic. Click here for more details.

Files changed (31) hide show
  1. ai_edge_litert/__init__.py +1 -1
  2. ai_edge_litert/libpywrap_litert_common.so +0 -0
  3. {ai_edge_litert_nightly-1.4.0.dev20250813.dist-info → ai_edge_litert_nightly-1.4.0.dev20250814.dist-info}/METADATA +1 -1
  4. {ai_edge_litert_nightly-1.4.0.dev20250813.dist-info → ai_edge_litert_nightly-1.4.0.dev20250814.dist-info}/RECORD +6 -31
  5. ai_edge_litert/aot/__init__.py +0 -0
  6. ai_edge_litert/aot/ai_pack/__init__.py +0 -0
  7. ai_edge_litert/aot/ai_pack/export_lib.py +0 -281
  8. ai_edge_litert/aot/aot_compile.py +0 -152
  9. ai_edge_litert/aot/core/__init__.py +0 -0
  10. ai_edge_litert/aot/core/apply_plugin.py +0 -146
  11. ai_edge_litert/aot/core/common.py +0 -95
  12. ai_edge_litert/aot/core/components.py +0 -93
  13. ai_edge_litert/aot/core/mlir_transforms.py +0 -36
  14. ai_edge_litert/aot/core/tflxx_util.py +0 -30
  15. ai_edge_litert/aot/core/types.py +0 -374
  16. ai_edge_litert/aot/prepare_for_npu.py +0 -152
  17. ai_edge_litert/aot/vendors/__init__.py +0 -18
  18. ai_edge_litert/aot/vendors/example/__init__.py +0 -0
  19. ai_edge_litert/aot/vendors/example/example_backend.py +0 -157
  20. ai_edge_litert/aot/vendors/fallback_backend.py +0 -128
  21. ai_edge_litert/aot/vendors/import_vendor.py +0 -132
  22. ai_edge_litert/aot/vendors/mediatek/__init__.py +0 -0
  23. ai_edge_litert/aot/vendors/mediatek/mediatek_backend.py +0 -196
  24. ai_edge_litert/aot/vendors/mediatek/target.py +0 -91
  25. ai_edge_litert/aot/vendors/qualcomm/__init__.py +0 -0
  26. ai_edge_litert/aot/vendors/qualcomm/qualcomm_backend.py +0 -161
  27. ai_edge_litert/aot/vendors/qualcomm/target.py +0 -74
  28. ai_edge_litert/libLiteRtRuntimeCApi.so +0 -0
  29. ai_edge_litert/tools/apply_plugin_main +0 -0
  30. {ai_edge_litert_nightly-1.4.0.dev20250813.dist-info → ai_edge_litert_nightly-1.4.0.dev20250814.dist-info}/WHEEL +0 -0
  31. {ai_edge_litert_nightly-1.4.0.dev20250813.dist-info → ai_edge_litert_nightly-1.4.0.dev20250814.dist-info}/top_level.txt +0 -0
@@ -1 +1 @@
1
- __version__ = "1.4.0.dev20250813"
1
+ __version__ = "1.4.0.dev20250814"
Binary file
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ai-edge-litert-nightly
3
- Version: 1.4.0.dev20250813
3
+ Version: 1.4.0.dev20250814
4
4
  Summary: LiteRT is for mobile and embedded devices.
5
5
  Home-page: https://www.tensorflow.org/lite/
6
6
  Author: Google AI Edge Authors
@@ -1,4 +1,4 @@
1
- ai_edge_litert/__init__.py,sha256=IldzDEKlTmxzLLoGNY0HlSynO81y6L2E-oKhiyTvgZc,34
1
+ ai_edge_litert/__init__.py,sha256=_8wnWQPu-Jzh5AhwdogIQzRrnYwgDBb0b51yQ0pL8ng,34
2
2
  ai_edge_litert/_pywrap_analyzer_wrapper.so,sha256=qhOo4FG4sHlk0LRBUnHeXCZKhHGKgrzmA0WjmIFpPe8,6464
3
3
  ai_edge_litert/_pywrap_litert_compiled_model_wrapper.so,sha256=RRsmEAo9KuLT8lx0o8pIrS7zbwtYhHNLsvTx5hTyA-0,6488
4
4
  ai_edge_litert/_pywrap_litert_tensor_buffer_wrapper.so,sha256=-3w_TOE2Fnav4vc2ZN3aXtqcDhJP8RXpImo7AmUrpBk,6488
@@ -17,8 +17,7 @@ ai_edge_litert/field_mask_pb2.py,sha256=YVi1IasKjEQAlcIwM6HMgmW0wT6TMAXjiaiysrEY
17
17
  ai_edge_litert/format_converter_wrapper_pybind11.so,sha256=tIhiUYnHh5ZKIDTuMKKuOMwqxd6MjrPN7EMYV7oNO-M,6512
18
18
  ai_edge_litert/hardware_accelerator.py,sha256=FgouirT1Cs80mqvMvLbO9O7wiPBnQaWDB5vjFpJhtJo,800
19
19
  ai_edge_litert/interpreter.py,sha256=4u9FfiaYkDxf_IxCjzeLWyTyxwG184uVxqg0fbj6tYg,40650
20
- ai_edge_litert/libLiteRtRuntimeCApi.so,sha256=bH-yyyoIM8RPfSIuI_iCuHIa-cywj0saiHn7eA1NuXM,8920576
21
- ai_edge_litert/libpywrap_litert_common.so,sha256=SQTEkbQxmuayam5cVbqzOUgBjObS1Bg0uHJCxsXMfo8,14716272
20
+ ai_edge_litert/libpywrap_litert_common.so,sha256=91z0KyAIZZH8ipaDL_MjV987Hodwhc68HoHpQnmcDOE,15317624
22
21
  ai_edge_litert/metrics_interface.py,sha256=dVu6SmbnQUntPgE5o6BxHVMyemwli-7F6tDfVMGrlYI,1542
23
22
  ai_edge_litert/metrics_portable.py,sha256=KKvR9ZOe8j2ZeBtDo_6gWJ8kENKoOawPK3LPkevnZa8,2039
24
23
  ai_edge_litert/model_runtime_info_pb2.py,sha256=E93kYJtWnsChrdegZJbKzeFpplssBGEURTdOOfjtOxg,6370
@@ -32,31 +31,7 @@ ai_edge_litert/tensor_buffer.py,sha256=3Xy7kd_aR499QrfO0YITvr_z-aU1eONga41KiDBUe
32
31
  ai_edge_litert/timestamp_pb2.py,sha256=K7Gs_qOn2XAMZTNUUrJ1XcGf4OmYhdt858I_zDtZYzg,1793
33
32
  ai_edge_litert/type_pb2.py,sha256=x8rTulmlk9FxtRJal7BnUsaPbn2TcLlu8D7AVoVPjMA,5065
34
33
  ai_edge_litert/wrappers_pb2.py,sha256=4hQAZRGeaE5DyY6YQ7VfrqozPa_d_LCOBEYjxfQNlKs,2955
35
- ai_edge_litert/aot/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
36
- ai_edge_litert/aot/aot_compile.py,sha256=i0c6owaMBT7N2VUUSk8KrP35XX0R9-c5XzTHQQRBIcU,5501
37
- ai_edge_litert/aot/prepare_for_npu.py,sha256=bghtIcLXw5P6u_lHOh-oBv4u-jCoUi-kI3wF3wA1Mow,5494
38
- ai_edge_litert/aot/ai_pack/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
39
- ai_edge_litert/aot/ai_pack/export_lib.py,sha256=KVzfU2zZ0c6hx0dC_nLMPYUr8NROacknUH6e-MFMWfE,10237
40
- ai_edge_litert/aot/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
41
- ai_edge_litert/aot/core/apply_plugin.py,sha256=DAWj1I9k94WCkwophgz5Nrj8A0kSO2v8X3nqN_1KJFk,4554
42
- ai_edge_litert/aot/core/common.py,sha256=5imHTXV2abVwd5RJqFD0iw6WlLZ73njOPtCUccYtrWM,3103
43
- ai_edge_litert/aot/core/components.py,sha256=DcdEDEiA6U0HT5Tt10aw_j_M1I-XtRiXTwE5hGBMEiI,2415
44
- ai_edge_litert/aot/core/mlir_transforms.py,sha256=cW1DWZX1FDEI87Ihf3CfJ31lQmfZEBLLdptQCsK4sjM,1289
45
- ai_edge_litert/aot/core/tflxx_util.py,sha256=fyg_K1-nVaEx207sZ88m9TOp3VcjJWpSFknv9_S8cF0,1020
46
- ai_edge_litert/aot/core/types.py,sha256=Bvv27bUQPGQSZON2bQZ8BZTxoxLDvQki6oqtymp6fx4,10547
47
- ai_edge_litert/aot/vendors/__init__.py,sha256=K11L1REFCE0umYEUwmTxhijRfVbIytqOych2QgP4b78,864
48
- ai_edge_litert/aot/vendors/fallback_backend.py,sha256=LvvnXyR-EANTzh9DOYwSGstoYYcsQxtxNyc5vb9P7qE,3396
49
- ai_edge_litert/aot/vendors/import_vendor.py,sha256=HNDkx9vdmDGtX1SupfChKdW4UtCA8Xb6xC_S7xdBKkU,3469
50
- ai_edge_litert/aot/vendors/example/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
51
- ai_edge_litert/aot/vendors/example/example_backend.py,sha256=dgwTivJQzL1z3M_w4ixmOe_681E6cZW0bupgRPM_zOM,4182
52
- ai_edge_litert/aot/vendors/mediatek/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
53
- ai_edge_litert/aot/vendors/mediatek/mediatek_backend.py,sha256=uFSciDUollsKciJooxn5Fo7FWdAidSG0Q0BRBxE8TQI,6074
54
- ai_edge_litert/aot/vendors/mediatek/target.py,sha256=MvwdgybSHmVYuN1txgzmDUvO5HYubx9TLzOi1TXkJx4,2214
55
- ai_edge_litert/aot/vendors/qualcomm/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
56
- ai_edge_litert/aot/vendors/qualcomm/qualcomm_backend.py,sha256=121jVb4u1slOQ8FSf1vJBNiq1OPIMeNB9cEQrrWByJk,4864
57
- ai_edge_litert/aot/vendors/qualcomm/target.py,sha256=BesYeOdRQILJY2GRVzenakTWQU-fCTqs9VPTTLAA8mw,1796
58
- ai_edge_litert/tools/apply_plugin_main,sha256=43hZ-dPuf-gqxNqsE_rBWTC_ZllZcmAtTB0L_29msOg,2561952
59
- ai_edge_litert_nightly-1.4.0.dev20250813.dist-info/METADATA,sha256=bkiv0hJ0iTLL5N-NIQsyGKNwAhlBZsv_cDpL6Kxq_yU,1911
60
- ai_edge_litert_nightly-1.4.0.dev20250813.dist-info/WHEEL,sha256=2V3Z1XExrBUQtUy2R-D_eV91jXaDJRE0crbndTl2Q00,112
61
- ai_edge_litert_nightly-1.4.0.dev20250813.dist-info/top_level.txt,sha256=WcDZgG99n0a0xDS_ipL8ZWy956g1v5fVyR3FH96VDT0,15
62
- ai_edge_litert_nightly-1.4.0.dev20250813.dist-info/RECORD,,
34
+ ai_edge_litert_nightly-1.4.0.dev20250814.dist-info/METADATA,sha256=uUlRPU3OhyxzwH9YEEuY1K8ltKCBP4j4HCL9umv5zQ8,1911
35
+ ai_edge_litert_nightly-1.4.0.dev20250814.dist-info/WHEEL,sha256=2V3Z1XExrBUQtUy2R-D_eV91jXaDJRE0crbndTl2Q00,112
36
+ ai_edge_litert_nightly-1.4.0.dev20250814.dist-info/top_level.txt,sha256=WcDZgG99n0a0xDS_ipL8ZWy956g1v5fVyR3FH96VDT0,15
37
+ ai_edge_litert_nightly-1.4.0.dev20250814.dist-info/RECORD,,
File without changes
File without changes
@@ -1,281 +0,0 @@
1
- # Copyright 2025 Google LLC.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- """Utility functions for exporting models to AI pack format."""
15
-
16
- import itertools
17
- import os
18
- import pathlib
19
- from typing import cast
20
-
21
- from ai_edge_litert.aot.core import common
22
- from ai_edge_litert.aot.core import types
23
- from ai_edge_litert.aot.vendors import fallback_backend
24
- from ai_edge_litert.aot.vendors.mediatek import mediatek_backend
25
- from ai_edge_litert.aot.vendors.mediatek import target as mtk_target
26
- from ai_edge_litert.aot.vendors.qualcomm import qualcomm_backend
27
- from ai_edge_litert.aot.vendors.qualcomm import target as qnn_target
28
-
29
- # TODO: b/407453529 - Add unittests.
30
-
31
-
32
- _DEVICE_TARGETING_CONFIGURATION = """<config:device-targeting-config
33
- xmlns:config="http://schemas.android.com/apk/config">
34
- {device_groups}
35
- </config:device-targeting-config>"""
36
-
37
- _DEVICE_GROUP_TEMPLATE = """ <config:device-group name="{device_group_name}">
38
- {device_selectors}
39
- </config:device-group>"""
40
-
41
- _DEVICE_SELECTOR_TEMPLATE = """ <config:device-selector>
42
- <config:system-on-chip manufacturer="{soc_man}" model="{soc_model}"/>
43
- </config:device-selector>"""
44
-
45
-
46
- def _is_mobile_device_backend(backend: types.Backend):
47
- target = backend.target
48
- if backend.id() == qualcomm_backend.QualcommBackend.id():
49
- target = cast(qnn_target.Target, target)
50
- # Non Android QNN targets.
51
- if target.soc_model in (
52
- qnn_target.SocModel.SA8255,
53
- qnn_target.SocModel.SA8295,
54
- ):
55
- return False
56
- return True
57
-
58
-
59
- def _export_model_files_to_ai_pack(
60
- compiled_models: types.CompilationResult,
61
- ai_pack_dir: pathlib.Path,
62
- ai_pack_name: str,
63
- litert_model_name: str,
64
- *,
65
- separate_mtk_ai_pack: bool = True,
66
- ):
67
- """Exports the model tflite files to the AI pack directory structure.
68
-
69
- Args:
70
- compiled_models: The compiled models to export.
71
- ai_pack_dir: The directory to export the AI pack to.
72
- ai_pack_name: The name of the AI pack.
73
- litert_model_name: The name of the model in the litert format.
74
- separate_mtk_ai_pack: Whether to separate the MTK AI pack. If True, the main
75
- AI pack will use the fallback model for MTK targets. The MTK AI pack will
76
- contain all MTK models, and empty directories for non-MTK targets.
77
- """
78
- fallback_model = None
79
- for backend, model in compiled_models.models_with_backend:
80
- if backend.target_id == fallback_backend.FallbackBackend.id():
81
- fallback_model = model
82
- assert fallback_model is not None, 'Fallback model is required.'
83
-
84
- model_export_dir = ai_pack_dir / ai_pack_name / 'src/main/assets'
85
- os.makedirs(model_export_dir, exist_ok=True)
86
- for backend, model in compiled_models.models_with_backend:
87
- if not _is_mobile_device_backend(backend):
88
- continue
89
- target_id = backend.target_id
90
- backend_id = backend.id()
91
- if backend_id == fallback_backend.FallbackBackend.id():
92
- target_id = 'other'
93
- elif backend_id == mediatek_backend.MediaTekBackend.id():
94
- target_id = backend.target_id.replace(
95
- mtk_target.SocManufacturer.MEDIATEK, 'Mediatek'
96
- )
97
- group_name = 'model#group_' + target_id
98
- export_dir = model_export_dir / group_name
99
- os.makedirs(export_dir, exist_ok=True)
100
- model_export_path = export_dir / (litert_model_name + common.DOT_TFLITE)
101
- if (
102
- separate_mtk_ai_pack
103
- and backend_id == mediatek_backend.MediaTekBackend.id()
104
- ):
105
- # Use the fallback model for MTK targets in main AI pack.
106
- model_to_export = fallback_model
107
- else:
108
- model_to_export = model
109
- if not model_to_export.in_memory:
110
- model_to_export.load()
111
- model_to_export.save(model_export_path, export_only=True)
112
-
113
- if separate_mtk_ai_pack:
114
- _export_model_files_to_mtk_ai_pack(
115
- compiled_models=compiled_models,
116
- ai_pack_dir=ai_pack_dir,
117
- ai_pack_name=ai_pack_name + '_mtk',
118
- litert_model_name=litert_model_name + '_mtk',
119
- )
120
-
121
-
122
- def _export_model_files_to_mtk_ai_pack(
123
- compiled_models: types.CompilationResult,
124
- ai_pack_dir: pathlib.Path,
125
- ai_pack_name: str,
126
- litert_model_name: str,
127
- ):
128
- """Exports the model tflite files to the MTK AI pack directory structure."""
129
- model_export_dir = ai_pack_dir / ai_pack_name / 'src/main/assets'
130
- os.makedirs(model_export_dir, exist_ok=True)
131
- for backend, model in compiled_models.models_with_backend:
132
- if not _is_mobile_device_backend(backend):
133
- continue
134
- backend_id = backend.id()
135
- target_id = backend.target_id
136
- if backend_id == fallback_backend.FallbackBackend.id():
137
- target_id = 'other'
138
- elif backend_id == mediatek_backend.MediaTekBackend.id():
139
- target_id = backend.target_id.replace(
140
- mtk_target.SocManufacturer.MEDIATEK, 'Mediatek'
141
- )
142
- group_name = 'model#group_' + target_id
143
- export_dir = model_export_dir / group_name
144
- os.makedirs(export_dir, exist_ok=True)
145
- if backend_id != mediatek_backend.MediaTekBackend.id():
146
- # Skip non-MTK targets, just create a placeholder file.
147
- placeholder_file = export_dir / 'placeholder.txt'
148
- placeholder_file.touch()
149
- continue
150
- model_export_path = export_dir / (litert_model_name + common.DOT_TFLITE)
151
- if not model.in_memory:
152
- model.load()
153
- model.save(model_export_path, export_only=True)
154
-
155
-
156
- def _build_targeting_config(compiled_backends: list[types.Backend]) -> str:
157
- """Builds device-targeting-config in device_targeting_configuration.xml."""
158
- device_groups = []
159
- for backend in compiled_backends:
160
- if not _is_mobile_device_backend(backend):
161
- continue
162
- target = backend.target
163
- device_group = _target_to_ai_pack_info(target)
164
- if device_group:
165
- device_groups.append(device_group)
166
- device_groups = '\n'.join(device_groups)
167
- return _DEVICE_TARGETING_CONFIGURATION.format(device_groups=device_groups)
168
-
169
-
170
- def _target_to_ai_pack_info(target: types.Target) -> str | None:
171
- """Builds the device group used in device_targeting_configuration.xml."""
172
- if isinstance(target, qnn_target.Target):
173
- group_name = str(target)
174
- selector = _process_qnn_target(target)
175
- device_selectors = [
176
- _DEVICE_SELECTOR_TEMPLATE.format(soc_man=man, soc_model=model)
177
- for man, model in selector
178
- ]
179
- device_selectors = '\n'.join(device_selectors)
180
- device_group = _DEVICE_GROUP_TEMPLATE.format(
181
- device_group_name=group_name, device_selectors=device_selectors
182
- )
183
- return device_group
184
- elif isinstance(target, mtk_target.Target):
185
- group_name = str(target).replace(
186
- mtk_target.SocManufacturer.MEDIATEK, 'Mediatek'
187
- )
188
- # TODO: b/407453529 - Support MTK SDK Version / OS version in selector.
189
- selector = _process_mtk_target(target)
190
- device_selector = _DEVICE_SELECTOR_TEMPLATE.format(
191
- soc_man=selector[0], soc_model=selector[1]
192
- )
193
- device_group = _DEVICE_GROUP_TEMPLATE.format(
194
- device_group_name=group_name, device_selectors=device_selector
195
- )
196
- return device_group
197
- elif isinstance(target, fallback_backend.FallbackTarget):
198
- # Don't need to have device selector for fallback target.
199
- return None
200
- else:
201
- print('unsupported target ', target)
202
- return None
203
-
204
-
205
- # TODO: b/407453529 - Auto-generate this function from CSVs.
206
- def _process_qnn_target(target: qnn_target.Target) -> list[tuple[str, str]]:
207
- """Returns the list of (manufacturer, model) for the given QNN target."""
208
- # Play cannot distinguish between Qualcomm and QTI for now.
209
- manufacturer = ['Qualcomm', 'QTI']
210
- models = [str(target.soc_model)]
211
- return list(itertools.product(manufacturer, models))
212
-
213
-
214
- # TODO: b/407453529 - Auto-generate this function from CSVs.
215
- def _process_mtk_target(
216
- target: mtk_target.Target,
217
- ) -> tuple[str, str]:
218
- """Returns tuple of (manufacturer, model) for the given MTK target."""
219
- # Play cannot distinguish between Qualcomm and QTI for now.
220
- return str(target.soc_manufacturer).replace(
221
- mtk_target.SocManufacturer.MEDIATEK, 'Mediatek'
222
- ), str(target.soc_model)
223
-
224
-
225
- def _write_targeting_config(
226
- compiled_models: types.CompilationResult, ai_pack_dir: pathlib.Path
227
- ) -> None:
228
- """Writes device_targeting_configuration.xml for the given compiled models."""
229
- compiled_backends = [x for x, _ in compiled_models.models_with_backend]
230
- targeting_config = _build_targeting_config(
231
- compiled_backends=compiled_backends
232
- )
233
-
234
- targeting_config_path = ai_pack_dir / 'device_targeting_configuration.xml'
235
- targeting_config_path.write_text(targeting_config)
236
-
237
-
238
- def export(
239
- compiled_models: types.CompilationResult,
240
- ai_pack_dir: pathlib.Path | str,
241
- ai_pack_name: str,
242
- litert_model_name: str,
243
- ) -> None:
244
- """Exports the compiled models to AI pack format.
245
-
246
- This function will export the compiled models to corresponding directory
247
- structure:
248
-
249
- {ai_pack_dir}/
250
- AiPackManifest.xml
251
- device_targeting_configuration.xml
252
- {ai_pack_name}/src/main/assets/
253
- model#group_target_1/
254
- {litert_model_name}.tflite
255
- model#group_target_2/
256
- {litert_model_name}.tflite
257
- model#group_target_3/
258
- {litert_model_name}.tflite
259
- model#group_other/
260
- {litert_model_name}.tflite
261
-
262
- Args:
263
- compiled_models: The compiled models to export.
264
- ai_pack_dir: The directory to export the AI pack to.
265
- ai_pack_name: The name of the AI pack.
266
- litert_model_name: The name of the model in the litert format.
267
- """
268
- if isinstance(ai_pack_dir, str):
269
- ai_pack_dir = pathlib.Path(ai_pack_dir)
270
-
271
- ai_pack_dir.mkdir(parents=True, exist_ok=True)
272
-
273
- _export_model_files_to_ai_pack(
274
- compiled_models=compiled_models,
275
- ai_pack_dir=ai_pack_dir,
276
- ai_pack_name=ai_pack_name,
277
- litert_model_name=litert_model_name,
278
- )
279
- _write_targeting_config(
280
- compiled_models=compiled_models, ai_pack_dir=ai_pack_dir
281
- )
@@ -1,152 +0,0 @@
1
- # Copyright 2025 The LiteRT Authors. All Rights Reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- # ==============================================================================
15
-
16
- """AOT Compilation for LiteRT model."""
17
- import pathlib
18
- import tempfile
19
-
20
- from ai_edge_litert.aot import prepare_for_npu as core
21
- from ai_edge_litert.aot.core import apply_plugin
22
- from ai_edge_litert.aot.core import components
23
- from ai_edge_litert.aot.core import mlir_transforms
24
- from ai_edge_litert.aot.core import types
25
- from ai_edge_litert.aot.vendors import import_vendor
26
-
27
-
28
- def aot_compile(
29
- input_model: types.Model | str,
30
- output_dir: str | pathlib.Path | None = None,
31
- target: types.Target | list[types.Target] | None = None,
32
- config: (
33
- types.CompilationConfig | list[types.CompilationConfig] | None
34
- ) = None,
35
- quantizer: components.AieQuantizerT | None = None,
36
- keep_going: bool = True,
37
- subgraphs_to_compile: list[int] | None = None,
38
- **kwargs,
39
- ) -> types.CompilationResult:
40
- """Prepares a TFLite model for NPU execution.
41
-
42
- High level command that erforms various backend specific pre-processing steps
43
- and then applies an NPU compiler to the given model.
44
-
45
- Args:
46
- input_model: The input model to compile.
47
- output_dir: Directory to write the output files to. If not specified, the
48
- output files will be written to the same directory as the input file.
49
- target: The target to compile for. If not specified, will compile to all
50
- registered targets.
51
- config: The compilation config(s). Cannot be specified with target.
52
- quantizer: The quantizer to use for quantization.
53
- keep_going: Whether to keep going if some backends fail. If False, fail
54
- fast on the first error and raise an exception.
55
- subgraphs_to_compile: The subgraph index list to compile to NPU. If None,
56
- compile all subgraphs.
57
- **kwargs: Additional arguments to pass to the backend.
58
-
59
- Returns:
60
- Compiled models.
61
- """
62
- # Only one of target or config is needed.
63
- if target and config:
64
- raise ValueError("Cannot specify both target and config.")
65
-
66
- if config is None:
67
- if target is None:
68
- target = import_vendor.AllRegisteredTarget()
69
- if isinstance(target, types.Target):
70
- config = types.CompilationConfig(target=target)
71
- elif isinstance(target, list):
72
- config = [types.CompilationConfig(target=t) for t in target]
73
- else:
74
- raise ValueError("Unsupported target type.")
75
-
76
- if isinstance(input_model, str):
77
- input_path = pathlib.Path(input_model)
78
- input_model = types.Model.create_from_path(input_path)
79
-
80
- # Resolve output paths.
81
- temp_dir = None
82
- if not output_dir:
83
- if input_model.in_memory:
84
- # Use a temp dir for in-memory models.
85
- # The temp dir will be cleaned up after the models are compiled and loaded
86
- # back to memory (i.e. function returns).
87
- temp_dir = tempfile.TemporaryDirectory()
88
- output_dir = temp_dir.name
89
- else:
90
- input_path = input_model.path
91
- output_dir = input_path.parent / "_compiled_models"
92
- output_dir.mkdir(parents=True, exist_ok=True)
93
- output_dir = str(output_dir)
94
- output_dir_path = pathlib.Path(output_dir)
95
-
96
- if isinstance(config, types.CompilationConfig) or not config:
97
- if config:
98
- # Make pytype happy.
99
- assert isinstance(config, types.CompilationConfig)
100
- kw_config = config.to_dict() | kwargs
101
- else:
102
- kw_config = kwargs
103
-
104
- backend_class = core.resolve_backend(kw_config)
105
-
106
- quant_recipe = kw_config.get("quantize_recipe", None)
107
- if quant_recipe:
108
- assert quantizer is not None, "Quantizer is required for quantization."
109
-
110
- results = core.prepare_for_npu(
111
- input_model,
112
- output_dir_path,
113
- backend_class,
114
- kw_config,
115
- transforms=mlir_transforms.MlirTransforms(),
116
- quantizer=quantizer,
117
- plugin=apply_plugin.ApplyPlugin(
118
- experimental_capture_stderr=True,
119
- subgraphs_to_compile=subgraphs_to_compile,
120
- ),
121
- keep_going=keep_going,
122
- )
123
- elif isinstance(config, list):
124
- kw_configs = [c.to_dict() | kwargs for c in config]
125
-
126
- configs_with_backend = [(core.resolve_backend(c), c) for c in kw_configs]
127
- requires_quantizer = any("quantize_recipe" in c for c in kw_configs)
128
- if requires_quantizer and quantizer is None:
129
- raise ValueError("Quantizer is required for quantization.")
130
-
131
- results = core.prepare_for_npu_multiple_configs(
132
- input_model,
133
- output_dir_path,
134
- configs_with_backend,
135
- transforms=mlir_transforms.MlirTransforms(),
136
- quantizer=quantizer,
137
- plugin=apply_plugin.ApplyPlugin(
138
- experimental_capture_stderr=True,
139
- subgraphs_to_compile=subgraphs_to_compile,
140
- ),
141
- keep_going=keep_going,
142
- )
143
- else:
144
- # Should not reach here.
145
- raise ValueError("Unsupported config type.")
146
-
147
- if temp_dir:
148
- # Load the models to memory before cleaning up the temp dir.
149
- results.load()
150
- temp_dir.cleanup()
151
-
152
- return results
File without changes
@@ -1,146 +0,0 @@
1
- # Copyright 2024 The TensorFlow Authors. All Rights Reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- # ==============================================================================
15
-
16
- """Wrapper for calling the apply plugin tooling."""
17
-
18
-
19
- import os
20
- import pathlib
21
- import re
22
- import subprocess
23
- import tempfile
24
-
25
- from ai_edge_litert.aot.core import common
26
- from ai_edge_litert.aot.core import components
27
- from ai_edge_litert.aot.core import types
28
-
29
- _BINARY = pathlib.Path("tools/apply_plugin_main")
30
-
31
- _RE_PARTITION_STATS = re.compile(
32
- r"PartitionSubgraph: (\d+), selected num ops: (\d+), from totoal ops:"
33
- r" (\d+), num partitions: (\d+)"
34
- )
35
-
36
-
37
- class ApplyPlugin(components.ApplyPluginT):
38
- """Wrapper for calling the apply plugin tooling."""
39
-
40
- def __init__(
41
- self,
42
- experimental_capture_stderr: bool = False,
43
- subgraphs_to_compile: list[int] | None = None,
44
- ):
45
- self._experimental_capture_stderr = experimental_capture_stderr
46
- self._subgraphs_to_compile = subgraphs_to_compile
47
-
48
- @property
49
- def default_err(self) -> str:
50
- # NOTE: Capture stderr from underlying binary.
51
- return "--"
52
-
53
- @property
54
- def component_name(self) -> str:
55
- return "apply_plugin"
56
-
57
- def __call__(
58
- self,
59
- input_model: types.Model,
60
- output_model: types.Model,
61
- soc_manufacturer: str,
62
- soc_model: str,
63
- sdk_libs_path: str | None = None,
64
- **kwargs,
65
- ):
66
- """Applies a plugin to the input model.
67
-
68
- Args:
69
- input_model: The path to the input model.
70
- output_model: The path to the output model.
71
- soc_manufacturer: The SOC manufacturer of the plugin.
72
- soc_model: The SOC model of the plugin.
73
- sdk_libs_path: The path to the SDK libs. If not provided,
74
- the default SDK path will be used.
75
- **kwargs: Additional arguments to pass to the underlying binary.
76
-
77
- Returns:
78
- The output model.
79
-
80
- Raises:
81
- ValueError: If no tflite model was created by the underying binary.
82
- """
83
- if input_model.in_memory:
84
- tmp_file = tempfile.NamedTemporaryFile(mode="wb")
85
- input_model.save(tmp_file.name)
86
- else:
87
- tmp_file = None
88
-
89
- binary = common.get_resource(_BINARY)
90
- args = [
91
- str(binary),
92
- "--cmd=apply",
93
- f"--model={str(input_model.path)}",
94
- f"--o={str(output_model.path)}",
95
- f"--soc_manufacturer={soc_manufacturer}",
96
- f"--soc_model={soc_model}",
97
- f"--err={self.default_err}",
98
- ]
99
- extra_args = [f"--{key}={value}" for key, value in kwargs.items()]
100
- args.extend(extra_args)
101
- if self._subgraphs_to_compile:
102
- subgraphs_to_compile = ",".join(
103
- str(s) for s in self._subgraphs_to_compile
104
- )
105
- args.append(f"--subgraphs={subgraphs_to_compile}")
106
- env = os.environ.copy()
107
- ld_library_path = common.construct_ld_library_path()
108
- if ld_library_path:
109
- if sdk_libs_path:
110
- ld_library_path = f"{sdk_libs_path}{os.pathsep}{ld_library_path}"
111
- env["LD_LIBRARY_PATH"] = ld_library_path
112
-
113
- result = subprocess.run(
114
- args,
115
- check=False,
116
- text=True,
117
- stdout=subprocess.PIPE,
118
- stderr=subprocess.STDOUT,
119
- env=env,
120
- )
121
- if result.returncode:
122
- log_file = tempfile.NamedTemporaryFile(mode="w", delete=False)
123
- log_file.write(result.stdout)
124
- log_file.close()
125
- raise ValueError(
126
- f"{self.component_name} failed to apply plugin. See"
127
- f" {log_file.name} for details."
128
- )
129
-
130
- if not common.is_tflite(output_model.path):
131
- raise ValueError(f"{output_model.path} is not a TFLite model.")
132
-
133
- partition_stats = _RE_PARTITION_STATS.findall(result.stdout)
134
- output_model.partition_stats = types.PartitionStats(
135
- subgraph_stats=[
136
- types.SubgraphPartitionStats(
137
- subgraph_index=int(s[0]),
138
- num_ops_offloaded=int(s[1]),
139
- num_total_ops=int(s[2]),
140
- num_partitions_offloaded=int(s[3]),
141
- )
142
- for s in partition_stats
143
- ]
144
- )
145
- if tmp_file is not None:
146
- tmp_file.close()