-
Notifications
You must be signed in to change notification settings - Fork 10.9k
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
Refactor lora adapter support #8332
Merged
Merged
Changes from 20 commits
Commits
Show all changes
42 commits
Select commit
Hold shift + click to select a range
67c5e14
lora: load to devide buft
ngxson e9d7b6c
add patch tensor function
ngxson 4e28ad4
correct tensor patch
ngxson 1b4ffba
llama_lora_adapter_apply
ngxson b88ce0f
correct ggml_backend_tensor_copy
ngxson f6d090d
add llm_build_mm
ngxson a1666aa
Merge branch 'master' into xsn/fix_lora
ngxson 30faf1f
fix auto merge
ngxson 79e2982
update based on review comments
ngxson 847135a
add convert script
ngxson 712fecb
no more transpose A
ngxson 84288ff
add f16 convert
ngxson 41ced24
Merge branch 'master' into xsn/fix_lora
ngxson 0e16188
add metadata check
ngxson 6c617e2
add sanity check
ngxson 7a83f20
fix ftype
ngxson d52455f
add requirements
ngxson 802565c
fix requirements
ngxson 95b3eb0
fix outfile
ngxson 03d24ca
Merge pull request #8 from ngxson/xsn/fix_lora_convert
ngxson ee2b35c
conversion: only allow selected models
ngxson 713665d
fix types
ngxson f15167a
cuda : do not use dmmv if the tensor does not have enough cols
slaren 9841fbd
llama : lora fixes
slaren 4fe0861
Merge pull request #9 from ggerganov/sl/fix_fix_lora
ngxson 1faf7e5
do not disable mmap with lora
ngxson e68344c
Merge branch 'master' into xsn/fix_lora
ngxson 916e959
llm_build_lora_mm_id
ngxson 9d96328
convert_lora : MoE LoRA conversion support
compilade 8956543
convert_hf : simplify modify_tensors for InternLM2
compilade 87301bd
llama : use llm_build_lora_mm in most model graphs
compilade 703573f
Merge branch 'master' into xsn/fix_lora
ngxson 42415a4
auto scale
ngxson 5b18118
Revert "auto scale"
ngxson f68d092
remove redundant params
ngxson b704448
Merge branch 'master' into xsn/fix_lora
ngxson 9175f4b
Apply suggestions from code review
ngxson 0ba23ba
change kv metadata
ngxson b1c4069
move add_type to __init__
ngxson 4d9ac0f
Merge branch 'master' into xsn/fix_lora
ngxson d09382f
convert_hf : move add_type to main()
compilade 383b6bc
Merge branch 'master' into xsn/fix_lora
ngxson File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
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,145 @@ | ||
#!/usr/bin/env python3 | ||
# -*- coding: utf-8 -*- | ||
|
||
from __future__ import annotations | ||
|
||
import logging | ||
import argparse | ||
import os | ||
import sys | ||
import types | ||
from pathlib import Path | ||
from typing import TYPE_CHECKING, Iterable, Iterator | ||
|
||
import torch | ||
|
||
if TYPE_CHECKING: | ||
from torch import Tensor | ||
|
||
if 'NO_LOCAL_GGUF' not in os.environ: | ||
sys.path.insert(1, str(Path(__file__).parent / 'gguf-py')) | ||
import gguf | ||
|
||
# reuse model definitions from convert_hf_to_gguf.py | ||
from convert_hf_to_gguf import Model | ||
|
||
logger = logging.getLogger("lora-to-gguf") | ||
|
||
|
||
def parse_args() -> argparse.Namespace: | ||
parser = argparse.ArgumentParser( | ||
description="Convert a huggingface PEFT LoRA adapter to a GGML compatible file") | ||
parser.add_argument( | ||
"--outfile", type=Path, | ||
help="path to write to; default: based on input. {ftype} will be replaced by the outtype.", | ||
) | ||
parser.add_argument( | ||
"--outtype", type=str, choices=["f32", "f16", "bf16", "q8_0"], default="f16", | ||
help="output format - use f32 for float32, f16 for float16, bf16 for bfloat16, q8_0 for Q8_0", | ||
) | ||
parser.add_argument( | ||
"--bigendian", action="store_true", | ||
help="model is executed on big endian machine", | ||
) | ||
parser.add_argument( | ||
"--verbose", action="store_true", | ||
help="increase output verbosity", | ||
) | ||
parser.add_argument( | ||
"--base", type=Path, required=True, | ||
help="directory containing base model file", | ||
) | ||
parser.add_argument( | ||
"lora_path", type=Path, | ||
help="directory containing LoRA adapter file", | ||
) | ||
|
||
return parser.parse_args() | ||
|
||
|
||
if __name__ == '__main__': | ||
args = parse_args() | ||
logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO) | ||
|
||
ftype_map: dict[str, gguf.LlamaFileType] = { | ||
"f32": gguf.LlamaFileType.ALL_F32, | ||
"f16": gguf.LlamaFileType.MOSTLY_F16, | ||
"bf16": gguf.LlamaFileType.MOSTLY_BF16, | ||
"q8_0": gguf.LlamaFileType.MOSTLY_Q8_0, | ||
} | ||
ftype = ftype_map[args.outtype] | ||
|
||
dir_base_model = args.base | ||
dir_lora = args.lora_path | ||
input_json = os.path.join(dir_lora, "adapter_config.json") | ||
input_model = os.path.join(dir_lora, "adapter_model.bin") | ||
if args.outfile is not None: | ||
fname_out = args.outfile | ||
else: | ||
# output in the same directory as the model by default | ||
fname_out = dir_lora / 'ggml-lora-{ftype}.gguf' | ||
|
||
if os.path.exists(input_model): | ||
lora_model = torch.load(input_model, map_location="cpu") | ||
else: | ||
input_model = os.path.join(dir_lora, "adapter_model.safetensors") | ||
# lazy import load_file only if lora is in safetensors format. | ||
from safetensors.torch import load_file | ||
lora_model = load_file(input_model, device="cpu") | ||
|
||
# load base model | ||
logger.info(f"Loading base model: {dir_base_model.name}") | ||
hparams = Model.load_hparams(dir_base_model) | ||
with torch.inference_mode(): | ||
try: | ||
model_class = Model.from_model_architecture(hparams["architectures"][0]) | ||
except NotImplementedError: | ||
logger.error(f"Model {hparams['architectures'][0]} is not supported") | ||
sys.exit(1) | ||
|
||
model_instance = model_class(dir_base_model, ftype, fname_out, args.bigendian, False, False, None) | ||
logger.info("Set model parameters") | ||
model_instance.set_gguf_parameters() | ||
|
||
# adapter_config = json.load(input_json) | ||
model_instance.gguf_writer.add_string("training.type", "finetune_lora") | ||
|
||
map_tensors: dict[str, Tensor] = {} | ||
for tensor_name, tensor in lora_model.items(): | ||
orig_name = tensor_name.replace("base_model.model.", "") | ||
orig_name = orig_name.replace(".lora_A.weight", ".weight") | ||
orig_name = orig_name.replace(".lora_B.weight", ".weight") | ||
is_lora_a = ".lora_A.weight" in tensor_name | ||
is_lora_b = ".lora_B.weight" in tensor_name | ||
if not is_lora_a and not is_lora_b: | ||
logger.error(f"Unexpected name '{tensor_name}': Not a lora_A or lora_B tensor") | ||
sys.exit(1) | ||
dest_name = model_instance.map_tensor_name(orig_name) | ||
dest_name = f"{dest_name}.lora_a" if is_lora_a else f"{dest_name}.lora_b" | ||
# logger.info(f"{orig_name} --> {dest_name}") | ||
map_tensors[dest_name] = tensor | ||
|
||
# overwrite method | ||
def get_tensors(self) -> Iterator[tuple[str, Tensor]]: | ||
for name, tensor in map_tensors.items(): | ||
yield (name, tensor) | ||
|
||
# overwrite method | ||
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: | ||
del bid # unused | ||
# TODO: This will not take into account tensor transformations | ||
return [(name, data_torch)] | ||
|
||
# overwrite method | ||
def extra_f16_tensors(self, name: str, new_name: str, bid: int | None, n_dims: int) -> bool: | ||
del name, new_name, bid, n_dims # unused | ||
return ftype != gguf.LlamaFileType.ALL_F32 | ||
|
||
model_instance.get_tensors = types.MethodType(get_tensors, model_instance) | ||
model_instance.modify_tensors = types.MethodType(modify_tensors, model_instance) | ||
model_instance.extra_f16_tensors = types.MethodType(extra_f16_tensors, model_instance) | ||
|
||
model_instance.gguf_writer.add_quantization_version(gguf.GGML_QUANT_VERSION) | ||
logger.info("Exporting model...") | ||
model_instance.write() | ||
logger.info(f"Model successfully exported to {fname_out}") | ||
ngxson marked this conversation as resolved.
Show resolved
Hide resolved
|
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
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,2 @@ | ||
-r ./requirements-convert_hf_to_gguf.txt | ||
--extra-index-url https://download.pytorch.org/whl/cpu |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is quite a big TODO. It was the reason the previous script was removed. I think this needs to be handled on a model by model basis, and reject models not explicitly supported, otherwise it will lead to the creation of incorrect gguf lora files.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
modify_tensors
does different things in different cases. Sometimes it filters out tensors, sometimes it splits them, sometimes it stacks them, sometimes it duplicates them, sometimes it permutes them, and sometimes it changes the values (like for Gemma's norms).If lora A and B weight can be turned into a tensor with the same shape as the weight tensor they're affecting, then transformed with the original
modify_tensors
of themodel_instance
, then split back into A and B, then it would allow all supported models to work with this.But I'm not sure if this is doable or not, or if the
modify_tensors
functions should instead have a lora mode or something like that.Alternatively, there might be a way to make this work with some kind of
LazyLoraTensor
(although it might not be possible to usegguf.LazyBase
as a base class because it assumes a more direct mapping of operations) by giving a fake tensor with the weight shape to the originalmodify_tensors
of themodel_instance
, then doing some magic interceptions to gracefully handle shape and value transformations, to then output back the lora weights along with their names.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I thought about this, but it still be very tricky because not all transformations are the same. For example, MOE tensors are stacked into 3d tensor which totally change the shape of the output tensor.
On the other hands, simple matrix add or scale can be applied to only lora_B tensor (why keeping lora_A untouched). For row permutation, I tried with simple numpy script and observed that
LlamaModel.permute(B)*A == LlamaModel.permute(B*A)
, but not sure if it's a known mathematics property or not.Until now I fully understand why the old python script was removed. You're right, I think for now we should explicitly check if given model support lore --> gguf conversion or not. Probably adding
Model.support_lora()
, and for now enable only llama-only (without MOE, so no mixtral)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
So I modified the script to re-use
modify_tensors()
from the original model class. Also addedsupport_lora()
, so model not overriding this method will not be able to convert lora.Commit: ee2b35c
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Btw, I'm trying to list out some of the transformation in
modify_tensors
that are easy to support. I'll have a look in the future:norm.weight
==> gemma should be ok to supportLlamaModel.permute(B)*A == LlamaModel.permute(B*A)
at least observed on my tests (or maybe just coincident)BA*scale == (B*scale)*A
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@ngxson Thanks a lot for this! I've converted the LoRA with my convert script, and I'm getting the same text as the sample output, but only when I scale the LoRA by 2, not sure if that's expected:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@compilade great, thanks! The result looks correct.
I fine tuned with rank 64 and alpha 128 so
scale = 128/64 = 2
is correct.In fact, I should have taken the rank and alpha from
adapter_config.json
then save it to gguf, so that when load we can automatically set the scale. I did not do that because in theory, we could have different rank for each tensors. But after second thought, in practical, most fine tuning frameworks use the same rank for all tensors, so we should not have any problems with my initial idea.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@ngxson I've finally pushed to your branch the modifications making
convert_lora_to_gguf.py
more general.I've added the
alpha
astraining.lora.alpha
to the GGUFs made byconvert_lora_to_gguf.py
in 8956543. I did not store the rank (yet) because it can be taken from the tensor dimensions, but this can still be changed relatively easily.I've also made pretty much every model graph use
llm_build_lora_mm
instead ofggml_mul_mat
where it made sense in 87301bd. Otherwise LoRA adapters for other architectures thanllama
were not really applied.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Perfect, thanks @compilade !
After thinking more about it, I think we can add a kvtraining.lora.scale
to store the default scale value. For now it will be calculated by alpha/rank, and in the future if users use another training framework, they can add their own logic to calculate default scale (so should be future-proof)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Oh sorry I didn't see your modification inside
llm_build_lora_mm
. Yeah calculating scale differently for each tensor is better. I'm reverting my change 42415a4