onnx-ir 0.0.1__py3-none-any.whl → 0.1.0__py3-none-any.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 onnx-ir might be problematic. Click here for more details.

Files changed (45) hide show
  1. onnx_ir/__init__.py +23 -10
  2. onnx_ir/{_convenience.py → _convenience/__init__.py} +40 -102
  3. onnx_ir/_convenience/_constructors.py +213 -0
  4. onnx_ir/_core.py +857 -233
  5. onnx_ir/_display.py +2 -2
  6. onnx_ir/_enums.py +107 -5
  7. onnx_ir/_graph_comparison.py +2 -2
  8. onnx_ir/_graph_containers.py +268 -0
  9. onnx_ir/_io.py +57 -10
  10. onnx_ir/_linked_list.py +15 -7
  11. onnx_ir/_metadata.py +4 -3
  12. onnx_ir/_name_authority.py +2 -2
  13. onnx_ir/_polyfill.py +26 -0
  14. onnx_ir/_protocols.py +31 -13
  15. onnx_ir/_tape.py +139 -32
  16. onnx_ir/_thirdparty/asciichartpy.py +1 -4
  17. onnx_ir/_type_casting.py +18 -3
  18. onnx_ir/{_internal/version_utils.py → _version_utils.py} +2 -29
  19. onnx_ir/convenience.py +4 -2
  20. onnx_ir/external_data.py +401 -0
  21. onnx_ir/passes/__init__.py +8 -2
  22. onnx_ir/passes/_pass_infra.py +173 -56
  23. onnx_ir/passes/common/__init__.py +36 -0
  24. onnx_ir/passes/common/_c_api_utils.py +76 -0
  25. onnx_ir/passes/common/clear_metadata_and_docstring.py +60 -0
  26. onnx_ir/passes/common/constant_manipulation.py +232 -0
  27. onnx_ir/passes/common/inliner.py +331 -0
  28. onnx_ir/passes/common/onnx_checker.py +57 -0
  29. onnx_ir/passes/common/shape_inference.py +112 -0
  30. onnx_ir/passes/common/topological_sort.py +33 -0
  31. onnx_ir/passes/common/unused_removal.py +196 -0
  32. onnx_ir/serde.py +288 -124
  33. onnx_ir/tape.py +15 -0
  34. onnx_ir/tensor_adapters.py +122 -0
  35. onnx_ir/testing.py +197 -0
  36. onnx_ir/traversal.py +4 -3
  37. onnx_ir-0.1.0.dist-info/METADATA +53 -0
  38. onnx_ir-0.1.0.dist-info/RECORD +41 -0
  39. {onnx_ir-0.0.1.dist-info → onnx_ir-0.1.0.dist-info}/WHEEL +1 -1
  40. onnx_ir-0.1.0.dist-info/licenses/LICENSE +202 -0
  41. onnx_ir/_external_data.py +0 -323
  42. onnx_ir-0.0.1.dist-info/LICENSE +0 -22
  43. onnx_ir-0.0.1.dist-info/METADATA +0 -73
  44. onnx_ir-0.0.1.dist-info/RECORD +0 -26
  45. {onnx_ir-0.0.1.dist-info → onnx_ir-0.1.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,401 @@
1
+ # Copyright (c) ONNX Project Contributors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """External data related utilities."""
4
+
5
+ from __future__ import annotations
6
+
7
+ __all__ = [
8
+ "set_base_dir",
9
+ "unload_from_model",
10
+ "load_to_model",
11
+ "convert_tensors_to_external",
12
+ "convert_tensors_from_external",
13
+ ]
14
+
15
+ import dataclasses
16
+ import logging
17
+ import os
18
+ from collections.abc import Iterator, Sequence
19
+
20
+ from onnx_ir import _core, _enums, _protocols
21
+ from onnx_ir import traversal as _traversal
22
+ from onnx_ir._polyfill import zip
23
+
24
+ # Note: If needed in future, add these as parameters to the function calls
25
+ # align_offset: Offset will always be page aligned and alloction granularity aligned for mmap support. This is done by padding previous tensor data with zeros keeping same length. Tensor data will be aligned if > align_threshold
26
+ _ALIGN_OFFSET = True
27
+ # align_threshold: Alignment threshold for size of data. Having a low threshold will waste file space for small initializers. Only when tensor's data is > the page_align_threshold it will be force aligned.
28
+ _ALIGN_THRESHOLD = 1048576 # 1MB
29
+ # allocation_granularity: The allocation Granularity for mmap() support. Typically 64KB for Windows & 4KB for other OSes.
30
+ _ALLOCATION_GRANULARITY = 65536 # 64KB
31
+
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+
36
+ @dataclasses.dataclass
37
+ class _ExternalDataInfo:
38
+ """A class that stores information about a tensor that is to be stored as external data.
39
+
40
+ Attributes:
41
+ name: The name of the tensor that is to be stored as external data.
42
+ offset: The offset is used to determine where exactly in the file the external data is written to.
43
+ length: Stores the size of the tensor.
44
+ """
45
+
46
+ name: str | None
47
+ offset: int
48
+ length: int
49
+
50
+
51
+ def _all_tensors(
52
+ graph: _core.Graph | _core.GraphView, include_attributes: bool = False
53
+ ) -> Iterator[_protocols.TensorProtocol]:
54
+ """Iterate over all tensors in the graph.
55
+
56
+ Args:
57
+ graph: The graph to traverse tensors on.
58
+ include_attributes: Whether to include tensors in attributes.
59
+
60
+ Yields:
61
+ Tensors in the graph.
62
+ """
63
+ # Yield all tensors in initializers
64
+ for value in graph.initializers.values():
65
+ if value.const_value is not None:
66
+ yield value.const_value
67
+ if not include_attributes:
68
+ return
69
+ # Look at constant attributes in nodes
70
+ for node in _traversal.RecursiveGraphIterator(graph):
71
+ for attr in node.attributes.values():
72
+ if attr.is_ref():
73
+ continue
74
+ if attr.type == _enums.AttributeType.TENSOR and attr.value is not None:
75
+ yield attr.value
76
+ elif attr.type == _enums.AttributeType.TENSORS and attr.value is not None:
77
+ yield from attr.value
78
+
79
+
80
+ def set_base_dir(graph: _core.Graph | _core.GraphView, base_dir: str | os.PathLike) -> None:
81
+ """Set the base directory for external data in a graph.
82
+
83
+ Args:
84
+ graph: The graph to traverse tensors on.
85
+ base_dir: The base directory. This is the directory where the ONNX file is.
86
+ """
87
+ for tensor in _all_tensors(graph, include_attributes=True):
88
+ if isinstance(tensor, _core.ExternalTensor):
89
+ tensor.base_dir = base_dir
90
+
91
+
92
+ def _external_tensor_to_memory_tensor(
93
+ tensor: _protocols.TensorProtocol,
94
+ ) -> _protocols.TensorProtocol:
95
+ """Convert an external tensor to an in memory tensor.
96
+
97
+ Args:
98
+ tensor: An external tensor to load.
99
+ base_dir: Path of base directory.
100
+ relative_path: Path to which external data is to be stored, relative to the ONNX file.
101
+
102
+ Returns:
103
+ An ir.Tensor object with the data loaded into memory.
104
+ """
105
+ if not isinstance(tensor, _core.ExternalTensor):
106
+ raise TypeError(f"Expected ExternalTensor, got {type(tensor)}")
107
+ # Copy the data as the .numpy() call references data from a file whose data is eventually modified
108
+ tensor_data = tensor.numpy().copy()
109
+ tensor.release()
110
+ return _core.Tensor(tensor_data, name=tensor.name, dtype=tensor.dtype)
111
+
112
+
113
+ def _compute_new_offset(
114
+ current_offset: int,
115
+ tensor_size: int,
116
+ align_offset: bool = _ALIGN_OFFSET,
117
+ align_threshold: int = _ALIGN_THRESHOLD,
118
+ allocation_granularity: int = _ALLOCATION_GRANULARITY,
119
+ ) -> int:
120
+ """Compute the offset to align the tensor data based on the current offset.
121
+
122
+ Args:
123
+ current_offset: Current location in the file at which tensor data will be written to.
124
+ tensor_size: Size of the tensor data to be written to file.
125
+ align_offset: Offset will always be page aligned and alloction granularity aligned for mmap support. This is done by padding previous tensor data with zeros keeping same length. Tensor data will be aligned if > align_threshold
126
+ align_threshold: Alignment threshold for size of data. Having a low threshold will waste file space for small initializers. Only when tensor's data is > the page_align_threshold it will be force aligned.
127
+ allocation_granularity: The allocation Granularity for mmap() support. Typically 64KB for Windows & 4KB for other OSes.
128
+
129
+ Returns:
130
+ The updated offset value.
131
+ """
132
+ if align_offset and tensor_size > align_threshold:
133
+ alignment_factor = max(4096, allocation_granularity)
134
+ # Align to the next page or alloc granularity
135
+ return (current_offset + alignment_factor - 1) // alignment_factor * alignment_factor
136
+ return current_offset
137
+
138
+
139
+ def _compute_external_data_info(
140
+ tensor: _protocols.TensorProtocol,
141
+ current_offset: int,
142
+ ) -> _ExternalDataInfo:
143
+ """Capture information about a tensor that is to be stored as external data."""
144
+ tensor_size = tensor.nbytes
145
+ # Calculate updated offset and align tensors
146
+ current_offset = _compute_new_offset(current_offset, tensor_size)
147
+ # Store offset and tensor size as ExternalDataInfo
148
+ external_data_info = _ExternalDataInfo(
149
+ tensor.name,
150
+ current_offset,
151
+ tensor_size,
152
+ )
153
+ return external_data_info
154
+
155
+
156
+ def _write_external_data(
157
+ tensors: Sequence[_protocols.TensorProtocol],
158
+ external_data_infos: Sequence[_ExternalDataInfo],
159
+ file_path: str | os.PathLike,
160
+ ) -> None:
161
+ """Write tensor data to an external file according to information stored in ExternalDataInfo objects.
162
+
163
+ Args:
164
+ tensors: Tensors to be written as external data.
165
+ external_data_infos: External data information stored for each tensor to be written as external data.
166
+ file_path: Location to which external data is to be stored.
167
+ """
168
+ assert len(tensors) == len(external_data_infos), (
169
+ "Number of tensors and external data infos should match"
170
+ )
171
+ with open(file_path, "wb") as data_file:
172
+ for tensor, tensor_info in zip(tensors, external_data_infos, strict=True):
173
+ current_offset = tensor_info.offset
174
+ assert tensor is not None
175
+ raw_data = tensor.tobytes()
176
+ if isinstance(tensor, _core.ExternalTensor):
177
+ tensor.release()
178
+ # Pad file to required offset if needed
179
+ file_size = data_file.tell()
180
+ if current_offset > file_size:
181
+ data_file.write(b"\0" * (current_offset - file_size))
182
+ data_file.write(raw_data)
183
+
184
+
185
+ def _create_external_tensor(
186
+ tensor: _protocols.TensorProtocol,
187
+ external_data_info: _ExternalDataInfo,
188
+ base_dir: str | os.PathLike,
189
+ relative_path: str | os.PathLike,
190
+ ) -> _core.ExternalTensor:
191
+ """Create external tensors from external data information.
192
+
193
+ Args:
194
+ tensor: Tensor to be converted to external tensor.
195
+ external_data_info: External data information stored for the tensor to be written as external data.
196
+ base_dir: Path of base directory.
197
+ relative_path: Path to which external data is to be stored, relative to the ONNX file.
198
+
199
+ Returns:
200
+ External tensor created from the information.
201
+ """
202
+ return _core.ExternalTensor(
203
+ os.path.normpath(relative_path),
204
+ external_data_info.offset,
205
+ external_data_info.length,
206
+ tensor.dtype, # type: ignore[arg-type]
207
+ shape=tensor.shape, # type: ignore[arg-type]
208
+ name=tensor.name, # type: ignore[arg-type]
209
+ base_dir=os.path.normpath(base_dir),
210
+ )
211
+
212
+
213
+ def convert_tensors_from_external(
214
+ tensors: Sequence[_protocols.TensorProtocol],
215
+ ) -> list[_protocols.TensorProtocol]:
216
+ """Convert a sequence of external tensors to in-memory tensors.
217
+
218
+ Args:
219
+ tensors: External tensors to be converted to in-memory tensors.
220
+
221
+ Returns:
222
+ A list of in-memory tensors derived from a list of external tensors.
223
+ """
224
+ return [_external_tensor_to_memory_tensor(tensor) for tensor in tensors]
225
+
226
+
227
+ def convert_tensors_to_external(
228
+ tensors: Sequence[_protocols.TensorProtocol],
229
+ base_dir: str | os.PathLike,
230
+ relative_path: str | os.PathLike,
231
+ ) -> list[_core.ExternalTensor]:
232
+ """Convert a sequence of any TensorProtocol tensors to external tensors.
233
+
234
+ Existing external tensors are loaded to memory if they are referring to the
235
+ same file path as the destination path.
236
+
237
+ Args:
238
+ tensors: Tensors to be converted to external tensors. They can be external tensors themselves.
239
+ base_dir: Path of base directory.
240
+ relative_path: Path to which external data is to be stored, relative to the ONNX file.
241
+
242
+ Returns:
243
+ A list of external tensors derived from a list of input tensors. The order
244
+ should match the input tensor order.
245
+ """
246
+ path = os.path.join(base_dir, relative_path)
247
+
248
+ # Check if output path exists. Load pre-existing external data if it does.
249
+ if os.path.exists(path):
250
+ # Check if any tensor provided is using the destination file
251
+ new_tensors = []
252
+ for tensor in tensors:
253
+ if (
254
+ isinstance(tensor, _core.ExternalTensor)
255
+ and os.path.exists(tensor.path)
256
+ and os.path.samefile(path, tensor.path)
257
+ ):
258
+ # FIXME(shubhambhokare1): If there is a non-initializer tensor that
259
+ # is referring to this file, that tensor is now invalid.
260
+ # This is a special case we are ok not handling right now.
261
+ new_tensors.append(_external_tensor_to_memory_tensor(tensor))
262
+ # Mark the original external tensor as invalid because it is now pointing
263
+ # to a file that is going to be overwritten.
264
+ tensor.invalidate()
265
+ logger.warning(
266
+ "External tensor %s is referring to the same file as the destination path. "
267
+ "It has been invalidated because the data file is changed. To avoid this, "
268
+ "save the external data to a different path or load the newly saved model back "
269
+ "with ir.load().",
270
+ tensor,
271
+ )
272
+ else:
273
+ new_tensors.append(tensor)
274
+ tensors = new_tensors
275
+
276
+ external_data_infos: list[_ExternalDataInfo] = []
277
+ # Sort all tensors based on tensor sizes, in order to avoid unnecessary alignment.
278
+ # All the smaller tensors are written earlier and alignment is performed for the larger tensors.
279
+ sorted_indices = sorted(range(len(tensors)), key=lambda i: tensors[i].nbytes)
280
+ sorted_tensors = [tensors[i] for i in sorted_indices]
281
+
282
+ # Compute external data information for each tensor and write to disk
283
+ current_offset = 0
284
+ for tensor in sorted_tensors:
285
+ external_info = _compute_external_data_info(tensor, current_offset)
286
+ external_data_infos.append(external_info)
287
+ current_offset = external_info.offset + external_info.length
288
+ _write_external_data(sorted_tensors, external_data_infos, path)
289
+
290
+ # Create external tensor objects
291
+ external_tensors: list[_core.ExternalTensor] = [
292
+ _create_external_tensor(tensor, external_info, base_dir, relative_path)
293
+ for tensor, external_info in zip(sorted_tensors, external_data_infos, strict=True)
294
+ ]
295
+
296
+ # Sort external_tensors based on original key order. So that it can match the input tensor order
297
+ external_tensors = [
298
+ external_tensors[i]
299
+ for i in sorted(range(len(external_tensors)), key=lambda i: sorted_indices[i])
300
+ ]
301
+
302
+ return external_tensors
303
+
304
+
305
+ def load_to_model(model: _core.Model) -> _core.Model:
306
+ """Convert all external model initializers to memory tensors in-place.
307
+
308
+ All initializers in the main graph and subgraphs are handled.
309
+
310
+ Args:
311
+ model: Model to process.
312
+ """
313
+ # TODO(justinchuby): Load tensor attributes in subgraphs
314
+ values_to_convert = []
315
+ for graph in model.graphs():
316
+ for value in graph.initializers.values():
317
+ if value.const_value is None:
318
+ # Filter out the uninitialized initializer values
319
+ continue
320
+ if isinstance(value.const_value, _core.ExternalTensor):
321
+ values_to_convert.append(value)
322
+ loaded_tensors = convert_tensors_from_external(
323
+ [v.const_value for v in values_to_convert] # type: ignore[misc]
324
+ )
325
+ for value, tensor in zip(values_to_convert, loaded_tensors, strict=True):
326
+ value.const_value = tensor
327
+
328
+ # Return the model because we may change the implementation to an out of place one
329
+ # to keep the input unchanged
330
+ return model
331
+
332
+
333
+ def unload_from_model(
334
+ model: _core.Model,
335
+ base_dir: str | os.PathLike,
336
+ relative_path: str | os.PathLike,
337
+ *,
338
+ size_threshold_bytes: int = 0,
339
+ ) -> _core.Model:
340
+ """Convert all initializers equal or above size_threshold_bytes to external tensors in-place and save data to a single data file.
341
+
342
+ It should only replace the initializers in the model with external tensors
343
+ and not make any other modifications to the model.
344
+
345
+ If any existing external tensor
346
+ references the provided ``external_data`` path, it will be invalidated
347
+ after the external data is overwritten. To obtain a valid model, use :func:`load`
348
+ to load the newly saved model, or provide a different external data path that
349
+ is not currently referenced by any tensors in the model.
350
+
351
+ All initializers in the main graph and subgraphs are handled.
352
+
353
+ Args:
354
+ model: Model to process.
355
+ base_dir: Path the directory where the ONNX model file is.
356
+ relative_path: Path to which external data is to be stored, relative to the ONNX file.
357
+ E.g. "model.data"
358
+ size_threshold_bytes: Save to external data if the tensor size in bytes is larger than this threshold.
359
+
360
+ Returns:
361
+ An ir.Model with all initializer data equal or above ``size_threshold_bytes``
362
+ converted to external tensors.
363
+ """
364
+ # In-memory or external tensors, if equal to or above the threshold, should be converted to or re-saved as external tensors
365
+ initializers_to_become_external = []
366
+ # Existing external tensors, if below the threshold, should be loaded to memory
367
+ initializers_to_load_to_memory = []
368
+ for graph in model.graphs():
369
+ for value in graph.initializers.values():
370
+ if value.const_value is None:
371
+ # Filter out the uninitialized initializer values
372
+ continue
373
+ if value.const_value.nbytes > size_threshold_bytes:
374
+ initializers_to_become_external.append(value)
375
+ elif isinstance(value.const_value, _core.ExternalTensor):
376
+ initializers_to_load_to_memory.append(value)
377
+
378
+ # Load to memory first, then convert to external tensors, because
379
+ # the existing external tensors may be overwritten by the new external data
380
+ memory_tensors = convert_tensors_from_external(
381
+ [v.const_value for v in initializers_to_load_to_memory] # type: ignore[misc]
382
+ )
383
+ external_tensors = convert_tensors_to_external(
384
+ [v.const_value for v in initializers_to_become_external], # type: ignore[misc]
385
+ base_dir=base_dir,
386
+ relative_path=relative_path,
387
+ )
388
+
389
+ # Replace the initializer values with external tensors and save the model
390
+ for value, external_tensor in zip(
391
+ initializers_to_become_external, external_tensors, strict=True
392
+ ):
393
+ value.const_value = external_tensor
394
+ for value, memory_tensor in zip(
395
+ initializers_to_load_to_memory, memory_tensors, strict=True
396
+ ):
397
+ value.const_value = memory_tensor
398
+
399
+ # Return the model because we may change the implementation to an out of place one
400
+ # to keep the input unchanged
401
+ return model
@@ -1,10 +1,13 @@
1
- # Copyright (c) Microsoft Corporation.
2
- # Licensed under the MIT License.
1
+ # Copyright (c) ONNX Project Contributors
2
+ # SPDX-License-Identifier: Apache-2.0
3
3
 
4
4
  __all__ = [
5
5
  "PassBase",
6
6
  "PassResult",
7
7
  "PassManager",
8
+ "Sequential",
9
+ "InPlacePass",
10
+ "FunctionalPass",
8
11
  # Errors
9
12
  "InvariantError",
10
13
  "PreconditionError",
@@ -13,6 +16,8 @@ __all__ = [
13
16
  ]
14
17
 
15
18
  from onnx_ir.passes._pass_infra import (
19
+ FunctionalPass,
20
+ InPlacePass,
16
21
  InvariantError,
17
22
  PassBase,
18
23
  PassError,
@@ -20,6 +25,7 @@ from onnx_ir.passes._pass_infra import (
20
25
  PassResult,
21
26
  PostconditionError,
22
27
  PreconditionError,
28
+ Sequential,
23
29
  )
24
30
 
25
31