Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove unnecessary constants for > 2GB ONNX models #1808

Merged
merged 2 commits into from
Apr 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 6 additions & 1 deletion optimum/exporters/onnx/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
from transformers.modeling_utils import get_parameter_dtype
from transformers.utils import is_tf_available, is_torch_available

from ...onnx.utils import _get_onnx_external_data_tensors, check_model_uses_external_data
from ...onnx.utils import _get_onnx_external_constants, _get_onnx_external_data_tensors, check_model_uses_external_data
from ...utils import (
DEFAULT_DUMMY_SHAPES,
ONNX_WEIGHTS_NAME,
Expand Down Expand Up @@ -592,6 +592,7 @@ def remap(value):

if model_uses_external_data or FORCE_ONNX_EXTERNAL_DATA:
tensors_paths = _get_onnx_external_data_tensors(onnx_model)
constant_paths = _get_onnx_external_constants(onnx_model)
logger.info("Saving external data to one file...")

# try free model memory
Expand All @@ -618,6 +619,10 @@ def remap(value):
for tensor in tensors_paths:
os.remove(output.parent / tensor)

for tensor in constant_paths:
if os.path.isfile(output.parent / tensor):
os.remove(output.parent / tensor)

return input_names, output_names


Expand Down
13 changes: 13 additions & 0 deletions optimum/onnx/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,19 @@
from onnx.external_data_helper import ExternalDataInfo, _get_initializer_tensors


def _get_onnx_external_constants(model: onnx.ModelProto) -> List[str]:
external_constants = []

for node in model.graph.node:
if node.op_type == "Constant":
for attribute in node.attribute:
external_datas = attribute.t.external_data
for external_data in external_datas:
external_constants.append(external_data.value)

return external_constants


def _get_onnx_external_data_tensors(model: onnx.ModelProto) -> List[str]:
"""
Gets the paths of the external data tensors in the model.
Expand Down