ai-edge-litert-nightly 1.4.0.dev20250729__cp311-cp311-macosx_12_0_arm64.whl → 1.4.0.dev20250814__cp311-cp311-macosx_12_0_arm64.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 (45) hide show
  1. ai_edge_litert/__init__.py +1 -1
  2. ai_edge_litert/any_pb2.py +4 -4
  3. ai_edge_litert/api_pb2.py +4 -4
  4. ai_edge_litert/descriptor_pb2.py +310 -118
  5. ai_edge_litert/duration_pb2.py +4 -4
  6. ai_edge_litert/empty_pb2.py +4 -4
  7. ai_edge_litert/field_mask_pb2.py +4 -4
  8. ai_edge_litert/model_runtime_info_pb2.py +4 -4
  9. ai_edge_litert/plugin_pb2.py +4 -4
  10. ai_edge_litert/profiling_info_pb2.py +4 -4
  11. ai_edge_litert/source_context_pb2.py +4 -4
  12. ai_edge_litert/struct_pb2.py +4 -4
  13. ai_edge_litert/timestamp_pb2.py +4 -4
  14. ai_edge_litert/type_pb2.py +4 -4
  15. ai_edge_litert/wrappers_pb2.py +4 -4
  16. {ai_edge_litert_nightly-1.4.0.dev20250729.dist-info → ai_edge_litert_nightly-1.4.0.dev20250814.dist-info}/METADATA +1 -1
  17. ai_edge_litert_nightly-1.4.0.dev20250814.dist-info/RECORD +36 -0
  18. ai_edge_litert/aot/__init__.py +0 -0
  19. ai_edge_litert/aot/ai_pack/__init__.py +0 -0
  20. ai_edge_litert/aot/ai_pack/export_lib.py +0 -281
  21. ai_edge_litert/aot/aot_compile.py +0 -152
  22. ai_edge_litert/aot/core/__init__.py +0 -0
  23. ai_edge_litert/aot/core/apply_plugin.py +0 -146
  24. ai_edge_litert/aot/core/common.py +0 -95
  25. ai_edge_litert/aot/core/components.py +0 -93
  26. ai_edge_litert/aot/core/mlir_transforms.py +0 -36
  27. ai_edge_litert/aot/core/tflxx_util.py +0 -30
  28. ai_edge_litert/aot/core/types.py +0 -374
  29. ai_edge_litert/aot/prepare_for_npu.py +0 -152
  30. ai_edge_litert/aot/vendors/__init__.py +0 -18
  31. ai_edge_litert/aot/vendors/example/__init__.py +0 -0
  32. ai_edge_litert/aot/vendors/example/example_backend.py +0 -157
  33. ai_edge_litert/aot/vendors/fallback_backend.py +0 -128
  34. ai_edge_litert/aot/vendors/import_vendor.py +0 -132
  35. ai_edge_litert/aot/vendors/mediatek/__init__.py +0 -0
  36. ai_edge_litert/aot/vendors/mediatek/mediatek_backend.py +0 -196
  37. ai_edge_litert/aot/vendors/mediatek/target.py +0 -91
  38. ai_edge_litert/aot/vendors/qualcomm/__init__.py +0 -0
  39. ai_edge_litert/aot/vendors/qualcomm/qualcomm_backend.py +0 -161
  40. ai_edge_litert/aot/vendors/qualcomm/target.py +0 -74
  41. ai_edge_litert/libLiteRtRuntimeCApi.so +0 -0
  42. ai_edge_litert/tools/apply_plugin_main +0 -0
  43. ai_edge_litert_nightly-1.4.0.dev20250729.dist-info/RECORD +0 -61
  44. {ai_edge_litert_nightly-1.4.0.dev20250729.dist-info → ai_edge_litert_nightly-1.4.0.dev20250814.dist-info}/WHEEL +0 -0
  45. {ai_edge_litert_nightly-1.4.0.dev20250729.dist-info → ai_edge_litert_nightly-1.4.0.dev20250814.dist-info}/top_level.txt +0 -0
@@ -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()
@@ -1,95 +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
- """Constants and other small generic utilities."""
17
-
18
- from importlib import resources
19
- import os
20
- import pathlib
21
-
22
- TFLITE = "tflite"
23
- DOT_TFLITE = f".{TFLITE}"
24
- NPU = "npu"
25
-
26
-
27
- _WORKSPACE_PREFIX = "litert"
28
- _AI_EDGE_LITERT_PREFIX = "ai_edge_litert"
29
- _LITERT_ROOT = ""
30
- _PYTHON_ROOT = "python/aot"
31
-
32
- MODULE_ROOT = ".".join([
33
- _WORKSPACE_PREFIX,
34
- _LITERT_ROOT.replace("/", "."),
35
- _PYTHON_ROOT.replace("/", "."),
36
- ])
37
-
38
-
39
- def get_resource(litert_relative_path: pathlib.Path) -> pathlib.Path:
40
- """Returns the path to a resource in the Litert workspace."""
41
- try:
42
- resource_root = resources.files(_WORKSPACE_PREFIX)
43
- except ModuleNotFoundError:
44
- resource_root = resources.files(_AI_EDGE_LITERT_PREFIX)
45
- litert_resource = resource_root.joinpath(
46
- _LITERT_ROOT, str(litert_relative_path)
47
- )
48
- if not litert_resource.is_file():
49
- raise FileNotFoundError(f"Resource {litert_resource} does not exist.")
50
- return pathlib.Path(str(litert_resource))
51
-
52
-
53
- def is_tflite(path: pathlib.Path) -> bool:
54
- return path.exists() and path.is_file() and path.suffix == f".{TFLITE}"
55
-
56
-
57
- def construct_ld_library_path() -> str:
58
- """Constructs a string suitable for the LD_LIBRARY_PATH environment variable.
59
-
60
- This function is used in ai_edge_litert python package, when the shared
61
- libraries are not in a static location. This function will construct the
62
- LD_LIBRARY_PATH environment variable using the ai_edge_litert directory, and
63
- all subdirectories.
64
-
65
- If the module is built from source, this function will return an empty string.
66
-
67
- Returns:
68
- A string suitable for the LD_LIBRARY_PATH environment variable.
69
- """
70
- try:
71
- resource_root = resources.files(_AI_EDGE_LITERT_PREFIX)
72
- except ModuleNotFoundError:
73
- # Bulit from source case.
74
- return ""
75
- root_package_path = str(resource_root)
76
-
77
- library_paths = set()
78
-
79
- library_paths.add(os.path.abspath(root_package_path))
80
-
81
- for dirpath, _, _ in os.walk(root_package_path):
82
- library_paths.add(os.path.abspath(dirpath))
83
-
84
- sorted_paths = sorted(list(library_paths))
85
- new_ld_library_path = os.pathsep.join(sorted_paths)
86
- current_ld_library_path = os.environ.get("LD_LIBRARY_PATH")
87
-
88
- if current_ld_library_path:
89
- if current_ld_library_path not in new_ld_library_path:
90
- lib_paths = f"{new_ld_library_path}{os.pathsep}{current_ld_library_path}"
91
- else:
92
- lib_paths = new_ld_library_path
93
- else:
94
- lib_paths = new_ld_library_path
95
- return lib_paths
@@ -1,93 +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
- """Interfaces for specific components used in the LiteRt AOT flow."""
17
-
18
- import abc
19
- import sys
20
- from typing import Any
21
-
22
- from ai_edge_litert.aot.core import types
23
-
24
- # pylint: disable=g-importing-member
25
- # pylint: disable=g-import-not-at-top
26
- # pylint: disable=g-bad-import-order
27
- if sys.version_info < (3, 10):
28
- from typing_extensions import TypeAlias
29
- else:
30
- from typing import TypeAlias
31
- # pylint: enable=g-bad-import-order
32
- # pylint: enable=g-import-not-at-top
33
- # pylint: enable=g-importing-member
34
-
35
- QuantRecipe: TypeAlias = list[dict[str, Any]] | str
36
-
37
-
38
- class AieQuantizerT(metaclass=abc.ABCMeta):
39
- """Interface for AIE quantizer components."""
40
-
41
- @property
42
- def component_name(self) -> str:
43
- return "aie_quantizer"
44
-
45
- @abc.abstractmethod
46
- def __call__(
47
- self,
48
- input_model: types.Model,
49
- output_model: types.Model,
50
- quantization_recipe: QuantRecipe | None = None,
51
- *args,
52
- **kwargs,
53
- ):
54
- pass
55
-
56
-
57
- class ApplyPluginT(metaclass=abc.ABCMeta):
58
- """Interface for apply plugin components."""
59
-
60
- @property
61
- def default_err(self) -> str:
62
- # NOTE: Capture stderr from underlying binary.
63
- return "none"
64
-
65
- @property
66
- def component_name(self) -> str:
67
- return "apply_plugin"
68
-
69
- @abc.abstractmethod
70
- def __call__(
71
- self,
72
- input_model: types.Model,
73
- output_model: types.Model,
74
- soc_manufacturer: str,
75
- soc_model: str,
76
- *args,
77
- **kwargs,
78
- ):
79
- pass
80
-
81
-
82
- class MlirTransformsT(metaclass=abc.ABCMeta):
83
- """Interface for MLIR transforms components."""
84
-
85
- @property
86
- def component_name(self) -> str:
87
- return "mlir_transforms"
88
-
89
- @abc.abstractmethod
90
- def __call__(
91
- self, input_model: types.Model, output_model: types.Model, *args, **kwargs
92
- ):
93
- pass
@@ -1,36 +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 suite of MLIR passes."""
17
-
18
- from ai_edge_litert.aot.core import components
19
- from ai_edge_litert.aot.core import tflxx_util
20
- from ai_edge_litert.aot.core import types
21
-
22
-
23
- class MlirTransforms(components.MlirTransformsT):
24
- """Wrapper for suite of MLIR passes."""
25
-
26
- def __call__(
27
- self,
28
- input_model: types.Model,
29
- output_model: types.Model,
30
- pass_name: str,
31
- ):
32
- if not input_model.in_memory:
33
- input_model.load()
34
- input_bytes = input_model.model_bytes
35
- output_bytes = tflxx_util.call_tflxx(input_bytes, pass_name)
36
- output_model.set_bytes(output_bytes)
@@ -1,30 +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
- # pylint: disable=g-import-not-at-top
17
- # pytype: disable=import-error
18
- # pytype: disable=not-callable
19
-
20
- """Shim layer for TFLXX while it is in experimental."""
21
-
22
-
23
- import importlib.util
24
- from typing import Callable
25
-
26
- call_tflxx: Callable[[bytes, str], bytes] = lambda input, pass_name: input
27
-
28
-
29
- def tflxx_enabled() -> bool:
30
- return False