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

load_in_4bit option for OVModelForCausalLM #538

Merged
merged 31 commits into from
Feb 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
7051462
Initial code for load_in_4_bit
AlexKoff88 Jan 29, 2024
491f25a
Dataset does not work
AlexKoff88 Jan 30, 2024
a08a16a
Intermediate changes
AlexKoff88 Jan 30, 2024
3ceea1d
Make it working with dataset
AlexKoff88 Jan 30, 2024
68d4f2d
Style
AlexKoff88 Jan 30, 2024
8b403da
Fixed small issue
AlexKoff88 Jan 30, 2024
0410b42
Fixed failed tests
AlexKoff88 Jan 30, 2024
7edffc8
Style
AlexKoff88 Jan 30, 2024
829cc6d
Comment failed tests due to NNCF 2.8
AlexKoff88 Jan 31, 2024
1e87775
Commented failed tests until new NNCF release
AlexKoff88 Jan 31, 2024
efe85a2
Added tests for load_in_4bit
AlexKoff88 Jan 31, 2024
6768527
Added awq option. Included NNCF package into openvino extra.
AlexKoff88 Feb 1, 2024
54f8fe0
Rolled back including nncf into openvino extra
AlexKoff88 Feb 1, 2024
2ec2a54
Style
AlexKoff88 Feb 1, 2024
c2f373f
Fixed tests
AlexKoff88 Feb 1, 2024
4c821ad
Fixed issues with models larger than 1B. Added tests.
AlexKoff88 Feb 2, 2024
9943624
Style
AlexKoff88 Feb 2, 2024
b555a67
Fixed issues. Applied comments.
AlexKoff88 Feb 5, 2024
9e108d7
Merge branch 'main' into ak/load_in_4bit_alt
AlexKoff88 Feb 5, 2024
55a673b
Removed unnecessary exception
AlexKoff88 Feb 5, 2024
374b1fc
Merged with main
AlexKoff88 Feb 5, 2024
f67e802
Applied more comments
AlexKoff88 Feb 5, 2024
de4d192
Fixed issue
AlexKoff88 Feb 5, 2024
277d39a
Make quantization_config a part of OVConfig in OVQuantizer
AlexKoff88 Feb 6, 2024
4707914
Fixed issue with Transformers
AlexKoff88 Feb 6, 2024
ae1da0f
Fixed test
AlexKoff88 Feb 7, 2024
1275d0a
Changed the naming. Added additional tests
AlexKoff88 Feb 8, 2024
ed69ff1
Fixed tests
AlexKoff88 Feb 8, 2024
c0e5a1a
Fixed tests
AlexKoff88 Feb 8, 2024
2922841
Applied more comments
AlexKoff88 Feb 8, 2024
a7eeeb2
Style
AlexKoff88 Feb 8, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions optimum/exporters/openvino/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ def _save_model(model, path: str, compression_option: Optional[str] = None, comp
"ratio": compression_ratio,
},
}

model = nncf.compress_weights(model, **COMPRESSION_OPTIONS[compression_option])

compress_to_fp16 = compression_option == "fp16"
Expand Down
15 changes: 12 additions & 3 deletions optimum/intel/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,12 @@
"OVQuantizer",
"OVTrainer",
"OVTrainingArguments",
"OVWeightQuantizationConfig",
]
else:
_import_structure["openvino"].extend(["OVConfig", "OVQuantizer", "OVTrainer", "OVTrainingArguments"])
_import_structure["openvino"].extend(
["OVConfig", "OVQuantizer", "OVTrainer", "OVTrainingArguments", "OVWeightQuantizationConfig"]
)

try:
if not (is_openvino_available() and is_diffusers_available()):
Expand Down Expand Up @@ -176,9 +179,15 @@
if not (is_openvino_available() and is_nncf_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from .utils.dummy_openvino_and_nncf_objects import OVConfig, OVQuantizer, OVTrainer, OVTrainingArguments
from .utils.dummy_openvino_and_nncf_objects import (
OVConfig,
OVQuantizer,
OVTrainer,
OVTrainingArguments,
OVWeightQuantizationConfig,
)
else:
from .openvino import OVConfig, OVQuantizer, OVTrainer, OVTrainingArguments
from .openvino import OVConfig, OVQuantizer, OVTrainer, OVTrainingArguments, OVWeightQuantizationConfig

try:
if not (is_openvino_available() and is_diffusers_available()):
Expand Down
1 change: 1 addition & 0 deletions optimum/intel/openvino/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from .quantization import OVQuantizer
from .trainer import OVTrainer
from .training_args import OVTrainingArguments
from .weight_quantization import OVWeightQuantizationConfig

from .modeling import (
OVModelForAudioClassification,
Expand Down
10 changes: 10 additions & 0 deletions optimum/intel/openvino/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,12 @@
from typing import Dict, List, Optional, Union

import torch
from transformers.utils.quantization_config import QuantizationConfigMixin

from optimum.configuration_utils import BaseConfig

from .weight_quantization import OVWeightQuantizationConfig


DEFAULT_QUANTIZATION_CONFIG = {
"algorithm": "quantization",
Expand Down Expand Up @@ -83,6 +86,7 @@ def __init__(
compression: Union[List[Dict], Dict, None] = None,
input_info: Optional[List] = None,
save_onnx_model: bool = False,
quantization_config: Optional[QuantizationConfigMixin] = None,
**kwargs,
):
super().__init__()
Expand All @@ -91,6 +95,7 @@ def __init__(
self.save_onnx_model = save_onnx_model
self._enable_standard_onnx_export_option()
self.optimum_version = kwargs.pop("optimum_version", None)
self.quantization_config = quantization_config

def add_input_info(self, model_inputs: Dict, force_batch_one: bool = False):
self.input_info = [
Expand All @@ -102,6 +107,11 @@ def add_input_info(self, model_inputs: Dict, force_batch_one: bool = False):
for name, value in model_inputs.items()
]

def save_pretrained(self, *args, **kwargs):
if self.quantization_config is None:
self.quantization_config = OVWeightQuantizationConfig()
super().save_pretrained(*args, **kwargs)

def _enable_standard_onnx_export_option(self):
# This method depends on self.save_onnx_model.
# save_onnx_model is defaulted to false so that the final model output is
Expand Down
18 changes: 13 additions & 5 deletions optimum/intel/openvino/modeling_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ def _from_pretrained(
from_onnx: bool = False,
local_files_only: bool = False,
load_in_8bit: bool = False,
load_in_4bit: bool = False,
**kwargs,
):
"""
Expand All @@ -186,13 +187,18 @@ def _from_pretrained(
force_download (`bool`, defaults to `False`):
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
cached versions if they exist.
file_name(`str`, *optional*):
file_name (`str`, *optional*):
The file name of the model to load. Overwrites the default file name and allows one to load the model
with a different name.
local_files_only(`bool`, *optional*, defaults to `False`):
local_files_only (`bool`, *optional*, defaults to `False`):
Whether or not to only look at local files (i.e., do not try to download the model).
load_in_8bit (`bool`, *optional*, defaults to `False`):
Whether or not to apply 8-bit weight quantization.
load_in_4bit (`bool`, *optional*, defaults to `False`):
Whether or not to apply 4-bit weight quantization.
"""

if load_in_4bit:
raise ValueError("load_in_4bit is available for OVModelForCausalLM only.")
model_path = Path(model_id)
default_file_name = ONNX_WEIGHTS_NAME if from_onnx else OV_XML_FILE_NAME
file_name = file_name or default_file_name
Expand Down Expand Up @@ -260,6 +266,7 @@ def _from_transformers(
task: Optional[str] = None,
trust_remote_code: bool = False,
load_in_8bit: Optional[bool] = None,
load_in_4bit: Optional[bool] = None,
**kwargs,
):
"""
Expand All @@ -283,9 +290,10 @@ def _from_transformers(
save_dir = TemporaryDirectory()
save_dir_path = Path(save_dir.name)

# If load_in_8bit is not specified then compression_option should be set to None and will be set by default in main_export depending on the model size
compression_option = None
if load_in_8bit is not None:
compression_option = "int8" if load_in_8bit else "fp32"
compression_option = "fp32"

main_export(
model_name_or_path=model_id,
Expand All @@ -302,7 +310,7 @@ def _from_transformers(
)

config.save_pretrained(save_dir_path)
return cls._from_pretrained(model_id=save_dir_path, config=config, load_in_8bit=False, **kwargs)
return cls._from_pretrained(model_id=save_dir_path, config=config, load_in_8bit=load_in_8bit, **kwargs)

@classmethod
def _to_load(
Expand Down
4 changes: 2 additions & 2 deletions optimum/intel/openvino/modeling_base_seq2seq.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ def _from_transformers(

compression_option = None
if load_in_8bit is not None:
compression_option = "int8" if load_in_8bit else "fp32"
compression_option = "fp32"
main_export(
model_name_or_path=model_id,
output=save_dir_path,
Expand All @@ -270,7 +270,7 @@ def _from_transformers(

config.save_pretrained(save_dir_path)
return cls._from_pretrained(
model_id=save_dir_path, config=config, use_cache=use_cache, load_in_8bit=False, **kwargs
model_id=save_dir_path, config=config, use_cache=use_cache, load_in_8bit=load_in_8bit, **kwargs
)

def _reshape(self, model: openvino.runtime.Model, batch_size: int, sequence_length: int, is_decoder=True):
Expand Down
54 changes: 46 additions & 8 deletions optimum/intel/openvino/modeling_decoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
from ..utils.modeling_utils import MULTI_QUERY_ATTN_MODELS
from .modeling import _TOKENIZER_FOR_DOC, INPUTS_DOCSTRING, MODEL_START_DOCSTRING, OVModel
from .utils import ONNX_WEIGHTS_NAME, OV_XML_FILE_NAME, STR_TO_OV_TYPE
from .weight_quantization import OVWeightQuantizationConfig, compress_decoder_weights


if is_transformers_version("<", "4.25.0"):
Expand Down Expand Up @@ -243,6 +244,8 @@ def _from_transformers(
use_cache: bool = True,
trust_remote_code: bool = False,
load_in_8bit: Optional[bool] = None,
load_in_4bit: Optional[bool] = None,
quantization_config: Optional[Union[OVWeightQuantizationConfig, Dict]] = None,
**kwargs,
):
if config.model_type.replace("_", "-") not in _SUPPORTED_ARCHITECTURES:
Expand All @@ -259,9 +262,10 @@ def _from_transformers(
if use_cache:
task = task + "-with-past"

# If load_in_8bit is not specified then compression_option should be set to None and will be set by default in main_export depending on the model size
compression_option = None
if load_in_8bit is not None:
compression_option = "int8" if load_in_8bit else "fp32"
if load_in_8bit is not None or load_in_4bit is not None:
compression_option = "fp32"
stateful = kwargs.pop("stateful", ensure_stateful_is_available(warn=False) and use_cache)
main_export(
model_name_or_path=model_id,
Expand All @@ -282,7 +286,14 @@ def _from_transformers(
config.is_encoder_decoder = False
config.save_pretrained(save_dir_path)
return cls._from_pretrained(
model_id=save_dir_path, config=config, use_cache=use_cache, load_in_8bit=False, stateful=None, **kwargs
model_id=save_dir_path,
config=config,
use_cache=use_cache,
load_in_8bit=load_in_8bit,
stateful=None,
load_in_4bit=load_in_4bit,
quantization_config=quantization_config,
**kwargs,
)

def _reshape(
Expand Down Expand Up @@ -356,15 +367,14 @@ class OVModelForCausalLM(OVBaseDecoderModel, GenerationMixin):
checkpoint="gpt2",
)
)
def forward(
def prepare_inputs(
self,
input_ids: torch.LongTensor,
attention_mask: Optional[torch.LongTensor] = None,
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
position_ids: Optional[torch.LongTensor] = None,
**kwargs,
) -> CausalLMOutputWithPast:
self.compile()
) -> Dict:
if self.use_cache and past_key_values is not None:
input_ids = input_ids[:, -1:]

Expand Down Expand Up @@ -449,6 +459,26 @@ def forward(
self.next_beam_idx if self.next_beam_idx is not None else np.arange(batch_size, dtype=int)
)

return inputs

def forward(
self,
input_ids: torch.LongTensor,
attention_mask: Optional[torch.LongTensor] = None,
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
position_ids: Optional[torch.LongTensor] = None,
**kwargs,
) -> CausalLMOutputWithPast:
self.compile()

inputs = self.prepare_inputs(
input_ids=input_ids,
attention_mask=attention_mask,
past_key_values=past_key_values,
position_ids=position_ids,
**kwargs,
)

# Run inference
self.request.start_async(inputs, share_inputs=True)
self.request.wait()
Expand Down Expand Up @@ -532,6 +562,8 @@ def _from_pretrained(
from_onnx: bool = False,
local_files_only: bool = False,
load_in_8bit: bool = False,
load_in_4bit: bool = False,
quantization_config: Union[OVWeightQuantizationConfig, Dict] = None,
**kwargs,
):
model_path = Path(model_id)
Expand All @@ -549,7 +581,9 @@ def _from_pretrained(
local_files_only=local_files_only,
)

model = cls.load_model(model_cache_path, load_in_8bit=load_in_8bit)
if load_in_8bit and load_in_4bit:
raise ValueError("Either load_in_8bit or load_in_4bit should be set to True.")
model = cls.load_model(model_cache_path, load_in_8bit=False if load_in_4bit else load_in_8bit)

model_type = config.model_type.replace("_", "-")
if model_type == "bloom":
Expand All @@ -563,7 +597,11 @@ def _from_pretrained(
else:
init_cls = cls

return init_cls(model=model, config=config, model_save_dir=model_cache_path.parent, **kwargs)
causal_model = init_cls(model=model, config=config, model_save_dir=model_cache_path.parent, **kwargs)

if load_in_4bit:
compress_decoder_weights(causal_model, quantization_config)
return causal_model


class OVBloomForCausalLM(OVModelForCausalLM):
Expand Down
Loading
Loading