LLaMA-Factory-Mirror/scripts/loftq_init.py

90 lines
3.3 KiB
Python
Raw Normal View History

2023-12-14 21:53:56 +08:00
# coding=utf-8
2024-06-15 17:54:33 +08:00
# Copyright 2024 HuggingFace Inc. and the LlamaFactory team.
#
2024-06-16 01:08:12 +08:00
# This code is based on the HuggingFace's PEFT library.
2024-06-15 17:54:33 +08:00
# https://github.com/huggingface/peft/blob/v0.10.0/examples/loftq_finetuning/quantize_save_load.py
#
# 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.
2023-12-14 21:53:56 +08:00
import os
2024-06-16 01:08:12 +08:00
from typing import TYPE_CHECKING
2024-01-20 20:15:56 +08:00
2023-12-14 21:53:56 +08:00
import fire
from peft import LoftQConfig, LoraConfig, TaskType, get_peft_model
2024-01-20 20:15:56 +08:00
from transformers import AutoModelForCausalLM, AutoTokenizer
2023-12-14 21:53:56 +08:00
2024-01-20 19:58:04 +08:00
if TYPE_CHECKING:
from transformers import PreTrainedModel
2023-12-14 21:53:56 +08:00
def quantize_loftq(
model_name_or_path: str,
2024-06-16 01:08:12 +08:00
output_dir: str,
loftq_bits: int = 4,
loftq_iter: int = 4,
lora_alpha: int = None,
lora_rank: int = 16,
lora_dropout: float = 0,
2024-06-26 19:43:16 +08:00
lora_target: tuple = ("q_proj", "v_proj"),
2024-06-16 01:08:12 +08:00
save_safetensors: bool = True,
2023-12-14 21:53:56 +08:00
):
2024-06-15 17:54:33 +08:00
r"""
Initializes LoRA weights with LoRA-fine-tuning-aware Quantization (LoftQ)
2024-06-16 01:08:12 +08:00
Usage: python loftq_init.py --model_name_or_path path_to_model --output_dir output_dir
2024-06-15 17:54:33 +08:00
"""
2024-06-26 19:43:16 +08:00
if isinstance(lora_target, str):
lora_target = [name.strip() for name in lora_target.split(",")]
2023-12-14 21:53:56 +08:00
tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(model_name_or_path, trust_remote_code=True, torch_dtype="auto")
2024-06-26 19:43:16 +08:00
2023-12-14 21:53:56 +08:00
loftq_config = LoftQConfig(loftq_bits=loftq_bits, loftq_iter=loftq_iter)
lora_config = LoraConfig(
task_type=TaskType.CAUSAL_LM,
inference_mode=True,
r=lora_rank,
lora_alpha=lora_alpha if lora_alpha is not None else lora_rank * 2,
2024-06-16 01:08:12 +08:00
lora_dropout=lora_dropout,
2024-06-26 19:43:16 +08:00
target_modules=lora_target,
2023-12-14 21:53:56 +08:00
init_lora_weights="loftq",
2024-01-20 20:15:56 +08:00
loftq_config=loftq_config,
2023-12-14 21:53:56 +08:00
)
# Init LoftQ model
2024-06-16 01:08:12 +08:00
print("Initializing LoftQ weights, it may be take several minutes, wait patiently.")
peft_model = get_peft_model(model, lora_config)
loftq_dir = os.path.join(output_dir, "loftq_init")
2023-12-14 21:53:56 +08:00
# Save LoftQ model
2024-07-24 16:56:58 +08:00
setattr(peft_model.peft_config["default"], "base_model_name_or_path", os.path.abspath(output_dir))
2024-06-16 01:08:12 +08:00
setattr(peft_model.peft_config["default"], "init_lora_weights", True) # don't apply loftq again
peft_model.save_pretrained(loftq_dir, safe_serialization=save_safetensors)
print("Adapter weights saved in {}".format(loftq_dir))
2023-12-14 21:53:56 +08:00
# Save base model
2024-06-16 01:08:12 +08:00
base_model: "PreTrainedModel" = peft_model.unload()
base_model.save_pretrained(output_dir, safe_serialization=save_safetensors)
tokenizer.save_pretrained(output_dir)
print("Model weights saved in {}".format(output_dir))
2024-06-17 17:47:25 +08:00
print("- Fine-tune this model with:")
2024-06-16 01:08:12 +08:00
print("model_name_or_path: {}".format(output_dir))
print("adapter_name_or_path: {}".format(loftq_dir))
print("finetuning_type: lora")
print("quantization_bit: {}".format(loftq_bits))
2023-12-14 21:53:56 +08:00
if __name__ == "__main__":
fire.Fire(quantize_loftq)