-
Notifications
You must be signed in to change notification settings - Fork 667
Enable inference with a merged decoder in ORTModelForCausalLM
#647
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
Changes from all commits
ec049f4
d899e34
eb0d2ef
a8b98b5
d3a9a1d
e399e8e
b76d3a1
04ff464
af3461b
a1d422c
0a5dd30
a7ec6ef
85603ee
2a8f3ca
167ae30
b5fe0a3
68e0025
babed4b
86cfc0a
f5051fb
fcec713
cd2deb2
102d0c8
496395c
b0d9c9a
995a976
6bd97b6
5c3b11b
0bcd528
44f7600
698bd70
5ada3ec
fb3feae
37acd6b
0eeb428
ea07a0e
14b616d
5cebc22
194108c
9c92ecc
04db6c4
164af2a
5edb255
4673963
d11d1ec
df6ef1d
67874f3
61878ce
ead4702
79aacee
badee2b
739d549
c176a8c
2b4fda5
d3cba91
edd8aab
0481ab2
8f8873b
4d0ef00
d3f68eb
2237300
4b15d40
3734803
d00c117
44df1c7
72beefc
f9a4c46
2b44e6d
8619f7c
2fc5d46
7a1b5b0
aaa9501
adf349a
81cfd98
0490518
3452fa5
e41a7c2
4f8d7d5
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -24,13 +24,19 @@ | |
| import re | ||
| from abc import ABC, abstractmethod | ||
| from collections import OrderedDict | ||
| from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Union | ||
| from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Tuple, Union | ||
|
|
||
| import onnx | ||
| from onnxruntime import InferenceSession | ||
| from onnxruntime import GraphOptimizationLevel, InferenceSession, SessionOptions | ||
| from transformers.utils import is_torch_available | ||
|
|
||
| from ...utils import DEFAULT_DUMMY_SHAPES, DummyInputGenerator, DummyTrainingLabelsInputGenerator, logging | ||
| from ...utils import ( | ||
| DEFAULT_DUMMY_SHAPES, | ||
| DummyInputGenerator, | ||
| DummyTrainingLabelsInputGenerator, | ||
| is_diffusers_available, | ||
| logging, | ||
| ) | ||
| from ...utils import TORCH_MINIMUM_VERSION as GLOBAL_MIN_TORCH_VERSION | ||
| from ...utils.doc import add_dynamic_docstring | ||
| from ..base import ExportConfig | ||
|
|
@@ -41,12 +47,11 @@ | |
|
|
||
| from transformers import PretrainedConfig, PreTrainedModel, TFPreTrainedModel | ||
|
|
||
|
|
||
| logger = logging.get_logger(__name__) | ||
| if is_diffusers_available(): | ||
| from diffusers import ModelMixin | ||
|
|
||
|
|
||
| # 2 Gb | ||
| EXTERNAL_DATA_FORMAT_SIZE_LIMIT = 2 * 1024 * 1024 * 1024 | ||
| logger = logging.get_logger(__name__) | ||
|
|
||
|
|
||
| @dataclasses.dataclass | ||
|
|
@@ -304,7 +309,9 @@ def fix_dynamic_axes(self, model_path: "Path", device: str = "cpu", input_shapes | |
| else: | ||
| providers = ["CPUExecutionProvider"] | ||
|
|
||
| session = InferenceSession(model_path.as_posix(), providers=providers) | ||
| session_options = SessionOptions() | ||
| session_options.graph_optimization_level = GraphOptimizationLevel.ORT_DISABLE_ALL # no need to optimize here | ||
| session = InferenceSession(model_path.as_posix(), providers=providers, sess_options=session_options) | ||
|
|
||
| to_fix = [] | ||
| for output_idx, node in enumerate(session.get_outputs()): | ||
|
|
@@ -463,14 +470,38 @@ def generate_dummy_inputs_for_validation(self, reference_model_inputs: Dict[str, | |
| """ | ||
| Generates inputs for ONNX Runtime using the reference model inputs. Override this to run inference with seq2seq | ||
| models which have the encoder and decoder exported as separate ONNX files. | ||
|
|
||
| Args: | ||
| reference_model_inputs ([`Dict[str, Tensor]`): | ||
| Reference inputs for the model. | ||
|
|
||
| Returns: | ||
| `Dict[str, Tensor]`: The mapping holding the kwargs to provide to the model's forward function | ||
| """ | ||
| return reference_model_inputs | ||
|
|
||
| def post_process_exported_models( | ||
| self, | ||
| path: "Path", | ||
| models_and_onnx_configs: Dict[ | ||
| str, Tuple[Union["PreTrainedModel", "TFPreTrainedModel", "ModelMixin"], "OnnxConfig"] | ||
| ], | ||
| onnx_files_subpaths: List[str], | ||
| ): | ||
| """ | ||
| Performs any model-specific post-processing on the ONNX. | ||
|
|
||
| Args: | ||
| path (`Path`): | ||
| Path to the directory of the stored ONNX model. | ||
| models_and_onnx_configs (`Dict[str, Tuple[Union["PreTrainedModel", "TFPreTrainedModel", "ModelMixin"], "OnnxConfig"]]`): | ||
| A dictionnary containing the models t apply post-processing on, and their corresponding ONNX configuration. | ||
| onnx_files_subpaths (`List[str]`): | ||
| The relative paths from the export directory to the ONNX files to do post-processing on. The order must be the same as* | ||
| the order of submodels in the ordered dict `models_and_onnx_configs`. | ||
| """ | ||
| return models_and_onnx_configs, onnx_files_subpaths | ||
|
|
||
|
|
||
| class OnnxConfigWithPast(OnnxConfig, ABC): | ||
| """ | ||
|
|
@@ -508,6 +539,8 @@ def __init__( | |
| f"use_past = {use_past} is different than use_present_in_outputs = {use_present_in_outputs}, the value " | ||
| "of use_present_in_outputs value will be used for the outputs." | ||
| ) | ||
| self.is_merged = False | ||
| self.use_cache_branch = None | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What's the difference between And does
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Yes, in other cases About the difference on
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
If you set only |
||
| super().__init__(config, task=task) | ||
|
|
||
| @classmethod | ||
|
|
@@ -559,7 +592,11 @@ def generate_dummy_inputs(self, framework: str = "pt", **kwargs): | |
| if dummy_input_gen.supports_input(input_name): | ||
| # models from TextSeq2SeqOnnxConfig use decoder_input_ids as input name | ||
| # while models from TextDecoderOnnxConfig use input_ids, hence the check for both | ||
| if self.use_past is True and input_name in ["decoder_input_ids", "input_ids"]: | ||
| if ( | ||
| self.use_past is True | ||
| and self.use_cache_branch is not False | ||
| and input_name in ["decoder_input_ids", "input_ids"] | ||
| ): | ||
| sequence_length = dummy_input_gen.sequence_length | ||
| if "sequence_length" in kwargs and kwargs["sequence_length"] != 1: | ||
| logger.info( | ||
|
|
@@ -579,7 +616,12 @@ def generate_dummy_inputs(self, framework: str = "pt", **kwargs): | |
| ) | ||
|
|
||
| # refer to https://github.com/huggingface/optimum/pull/764 | ||
| if self.use_past_in_inputs and "attention_mask" in dummy_inputs and self.PAD_ATTENTION_MASK_TO_PAST: | ||
| if ( | ||
| self.use_past_in_inputs | ||
| and self.PAD_ATTENTION_MASK_TO_PAST | ||
| and self.use_cache_branch is not False | ||
|
JingyaHuang marked this conversation as resolved.
|
||
| and "attention_mask" in dummy_inputs | ||
| ): | ||
| past_length = dummy_inputs["past_key_values"][0][0].shape[2] | ||
| dummy_inputs["attention_mask"] = DummyInputGenerator.pad_input_on_dim( | ||
| dummy_inputs["attention_mask"], | ||
|
|
@@ -807,6 +849,7 @@ def generate_dummy_inputs(self, framework: str = "pt", **kwargs): | |
| input_name, _ = next(iter(self._onnx_config.inputs.items())) | ||
| batch_size = dummy_inputs[input_name].shape[0] | ||
|
|
||
| # TODO: doesn't this break attention_mask generation? | ||
| if isinstance(self._onnx_config, OnnxSeq2SeqConfigWithPast) and self._onnx_config.use_past_in_inputs is True: | ||
| kwargs["sequence_length"] = 1 | ||
|
|
||
|
|
||


Uh oh!
There was an error while loading. Please reload this page.