-
Notifications
You must be signed in to change notification settings - Fork 115
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add openvino export configs and support chatglm
- Loading branch information
Showing
6 changed files
with
328 additions
and
27 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,9 @@ | ||
from .__main__ import main_export | ||
from .base import init_model_configs | ||
from .convert import export, export_models, export_pytorch_via_onnx | ||
from .model_configs import * | ||
|
||
|
||
init_model_configs() | ||
|
||
__all__ = ["main_export", "export", "export_models"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
from copy import deepcopy | ||
from typing import Callable, Type | ||
|
||
from optimum.exporters.tasks import TasksManager | ||
from optimum.utils.normalized_config import NormalizedConfigManager | ||
|
||
|
||
def init_model_configs(): | ||
suppored_models = TasksManager._SUPPORTED_MODEL_TYPE | ||
for model, export_configs in suppored_models.items(): | ||
if "onnx" not in export_configs: | ||
continue | ||
TasksManager._SUPPORTED_MODEL_TYPE[model]["openvino"] = deepcopy( | ||
TasksManager._SUPPORTED_MODEL_TYPE[model]["onnx"] | ||
) | ||
|
||
|
||
def register_normalized_config(model_type: str) -> Callable[[Type], Type]: | ||
def decorator(config_cls: Type) -> Type: | ||
if model_type in NormalizedConfigManager._conf: | ||
return config_cls | ||
NormalizedConfigManager._conf[model_type] = config_cls | ||
return config_cls | ||
|
||
return decorator |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
from typing import Optional, Tuple | ||
|
||
from optimum.utils import ( | ||
DEFAULT_DUMMY_SHAPES, | ||
DummyPastKeyValuesGenerator, | ||
DummyTextInputGenerator, | ||
NormalizedTextConfig, | ||
) | ||
|
||
|
||
class ChatGLN2DummyTextInputGenerator(DummyTextInputGenerator): | ||
SUPPORTED_INPUT_NAMES = { | ||
"input_ids", | ||
"attention_mask", | ||
"token_type_ids", | ||
"position_ids", | ||
} | ||
|
||
|
||
class ChatGLM2DummyPastKeyValuesGenerator(DummyPastKeyValuesGenerator): | ||
def __init__( | ||
self, | ||
task: str, | ||
normalized_config: NormalizedTextConfig, | ||
batch_size: int = DEFAULT_DUMMY_SHAPES["batch_size"], | ||
sequence_length: int = DEFAULT_DUMMY_SHAPES["sequence_length"], | ||
random_batch_size_range: Optional[Tuple[int, int]] = None, | ||
random_sequence_length_range: Optional[Tuple[int, int]] = None, | ||
**kwargs, | ||
): | ||
super().__init__( | ||
task=task, | ||
normalized_config=normalized_config, | ||
batch_size=batch_size, | ||
sequence_length=sequence_length, | ||
random_batch_size_range=random_batch_size_range, | ||
random_sequence_length_range=random_sequence_length_range, | ||
) | ||
self.multi_query_group_num = normalized_config.multi_query_group_num | ||
self.head_dim = self.hidden_size // self.num_attention_heads | ||
|
||
def generate(self, input_name: str, framework: str = "pt", int_dtype: str = "int64", float_dtype: str = "fp32"): | ||
past_key_shape = ( | ||
self.sequence_length, | ||
self.batch_size, | ||
self.multi_query_group_num, | ||
self.head_dim, | ||
) | ||
past_value_shape = ( | ||
self.sequence_length, | ||
self.batch_size, | ||
self.multi_query_group_num, | ||
self.head_dim, | ||
) | ||
return [ | ||
( | ||
self.random_float_tensor(past_key_shape, framework=framework, dtype=float_dtype), | ||
self.random_float_tensor(past_value_shape, framework=framework, dtype=float_dtype), | ||
) | ||
for _ in range(self.num_layers) | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
# Copyright 2022 The HuggingFace Team. All rights reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
from typing import Callable, Dict, Type | ||
|
||
from optimum.exporters.onnx import TextDecoderOnnxConfig | ||
from optimum.exporters.tasks import TasksManager, make_backend_config_constructor_for_task | ||
|
||
from .dummy_input_generators import ChatGLM2DummyPastKeyValuesGenerator, ChatGLN2DummyTextInputGenerator | ||
from .normalized_configs import ChatGLM2NormalizedConfig | ||
|
||
|
||
def create_register(overwrite_existing: bool = False): | ||
def wrapper(model_type: str, *supported_tasks: str) -> Callable[[Type], Type]: | ||
def decorator(config_cls: Type) -> Type: | ||
mapping = TasksManager._SUPPORTED_MODEL_TYPE.get(model_type, {}) | ||
mapping_backend = mapping.get("openvino", {}) | ||
for task in supported_tasks: | ||
normalized_task = task | ||
if "-with-past" in task: | ||
normalized_task = task.split("-with-past")[0] | ||
if normalized_task not in TasksManager.get_all_tasks(): | ||
known_tasks = ", ".join(TasksManager.get_all_tasks()) | ||
raise ValueError( | ||
f'The TasksManager does not know the task called "{task}", known tasks: {known_tasks}.' | ||
) | ||
if not overwrite_existing and task in mapping_backend: | ||
continue | ||
mapping_backend[task] = make_backend_config_constructor_for_task(config_cls, task) | ||
mapping["openvino"] = mapping_backend | ||
TasksManager._SUPPORTED_MODEL_TYPE[model_type] = mapping | ||
return config_cls | ||
|
||
return decorator | ||
|
||
return wrapper | ||
|
||
|
||
register_in_tasks_manager = create_register(True) | ||
|
||
|
||
@register_in_tasks_manager("chatglm", *["text-generation", "text-generation-with-past"]) | ||
class ChatGLM2OpenVINOConfig(TextDecoderOnnxConfig): | ||
NORMALIZED_CONFIG_CLASS = ChatGLM2NormalizedConfig | ||
DUMMY_INPUT_GENERATOR_CLASSES = (ChatGLN2DummyTextInputGenerator, ChatGLM2DummyPastKeyValuesGenerator) | ||
DUMMY_PKV_GENERATOR_CLASS = ChatGLM2DummyPastKeyValuesGenerator | ||
no_position_ids = False | ||
|
||
@property | ||
def inputs(self) -> Dict[str, Dict[int, str]]: | ||
common_inputs = super().inputs | ||
common_inputs.pop("attention_mask") | ||
if not self.no_position_ids and self.task == "text-generation": | ||
common_inputs["position_ids"] = {0: "batch_size", 1: "sequence_length"} | ||
|
||
return common_inputs | ||
|
||
def add_past_key_values(self, inputs_or_outputs: Dict[str, Dict[int, str]], direction: str): | ||
""" | ||
Fills `input_or_outputs` mapping with past_key_values dynamic axes considering the direction. | ||
Args: | ||
inputs_or_outputs (`Dict[str, Dict[int, str]]`): | ||
The mapping to fill. | ||
direction (`str`): | ||
either "inputs" or "outputs", it specifies whether `input_or_outputs` is the input mapping or the | ||
output mapping, this is important for axes naming. | ||
""" | ||
if direction not in ["inputs", "outputs"]: | ||
raise ValueError(f'direction must either be "inputs" or "outputs", but {direction} was given') | ||
|
||
if direction == "inputs": | ||
decoder_sequence_name = "past_sequence_length" | ||
name = "past_key_values" | ||
else: | ||
decoder_sequence_name = "past_sequence_length + 1" | ||
name = "present" | ||
|
||
for i in range(self._normalized_config.num_layers): | ||
inputs_or_outputs[f"{name}.{i}.key"] = {1: "batch_size", 0: decoder_sequence_name} | ||
inputs_or_outputs[f"{name}.{i}.value"] = {1: "batch_size", 0: decoder_sequence_name} |
Oops, something went wrong.