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

Refactor lora adapter support #8332

Merged
merged 42 commits into from
Jul 15, 2024
Merged
Show file tree
Hide file tree
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 Jul 6, 2024
e9d7b6c
add patch tensor function
ngxson Jul 6, 2024
4e28ad4
correct tensor patch
ngxson Jul 6, 2024
1b4ffba
llama_lora_adapter_apply
ngxson Jul 6, 2024
b88ce0f
correct ggml_backend_tensor_copy
ngxson Jul 6, 2024
f6d090d
add llm_build_mm
ngxson Jul 7, 2024
a1666aa
Merge branch 'master' into xsn/fix_lora
ngxson Jul 7, 2024
30faf1f
fix auto merge
ngxson Jul 7, 2024
79e2982
update based on review comments
ngxson Jul 8, 2024
847135a
add convert script
ngxson Jul 8, 2024
712fecb
no more transpose A
ngxson Jul 8, 2024
84288ff
add f16 convert
ngxson Jul 8, 2024
41ced24
Merge branch 'master' into xsn/fix_lora
ngxson Jul 8, 2024
0e16188
add metadata check
ngxson Jul 8, 2024
6c617e2
add sanity check
ngxson Jul 8, 2024
7a83f20
fix ftype
ngxson Jul 8, 2024
d52455f
add requirements
ngxson Jul 8, 2024
802565c
fix requirements
ngxson Jul 8, 2024
95b3eb0
fix outfile
ngxson Jul 8, 2024
03d24ca
Merge pull request #8 from ngxson/xsn/fix_lora_convert
ngxson Jul 8, 2024
ee2b35c
conversion: only allow selected models
ngxson Jul 9, 2024
713665d
fix types
ngxson Jul 9, 2024
f15167a
cuda : do not use dmmv if the tensor does not have enough cols
slaren Jul 10, 2024
9841fbd
llama : lora fixes
slaren Jul 10, 2024
4fe0861
Merge pull request #9 from ggerganov/sl/fix_fix_lora
ngxson Jul 10, 2024
1faf7e5
do not disable mmap with lora
ngxson Jul 10, 2024
e68344c
Merge branch 'master' into xsn/fix_lora
ngxson Jul 10, 2024
916e959
llm_build_lora_mm_id
ngxson Jul 10, 2024
9d96328
convert_lora : MoE LoRA conversion support
compilade Jul 9, 2024
8956543
convert_hf : simplify modify_tensors for InternLM2
compilade Jul 15, 2024
87301bd
llama : use llm_build_lora_mm in most model graphs
compilade Jul 15, 2024
703573f
Merge branch 'master' into xsn/fix_lora
ngxson Jul 15, 2024
42415a4
auto scale
ngxson Jul 15, 2024
5b18118
Revert "auto scale"
ngxson Jul 15, 2024
f68d092
remove redundant params
ngxson Jul 15, 2024
b704448
Merge branch 'master' into xsn/fix_lora
ngxson Jul 15, 2024
9175f4b
Apply suggestions from code review
ngxson Jul 15, 2024
0ba23ba
change kv metadata
ngxson Jul 15, 2024
b1c4069
move add_type to __init__
ngxson Jul 15, 2024
4d9ac0f
Merge branch 'master' into xsn/fix_lora
ngxson Jul 15, 2024
d09382f
convert_hf : move add_type to main()
compilade Jul 15, 2024
383b6bc
Merge branch 'master' into xsn/fix_lora
ngxson Jul 15, 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
11 changes: 3 additions & 8 deletions common/common.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2080,19 +2080,14 @@ std::tuple<struct llama_model *, struct llama_context *> llama_init_from_gpt_par
for (unsigned int i = 0; i < params.lora_adapter.size(); ++i) {
const std::string & lora_adapter = std::get<0>(params.lora_adapter[i]);
float lora_scale = std::get<1>(params.lora_adapter[i]);
int err = llama_model_apply_lora_from_file(model,
lora_adapter.c_str(),
lora_scale,
((i > 0) || params.lora_base.empty())
? NULL
: params.lora_base.c_str(),
params.n_threads);
if (err != 0) {
auto adapter = llama_lora_adapter_init(model, lora_adapter.c_str());
if (adapter == nullptr) {
fprintf(stderr, "%s: error: failed to apply lora adapter\n", __func__);
llama_free(lctx);
llama_free_model(model);
return std::make_tuple(nullptr, nullptr);
}
llama_lora_adapter_set(lctx, adapter, lora_scale);
}

if (params.ignore_eos) {
Expand Down
145 changes: 145 additions & 0 deletions convert_lora_to_gguf.py
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)]
Copy link
Member

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.

Copy link
Collaborator

@compilade compilade Jul 9, 2024

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 the model_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 use gguf.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 original modify_tensors of the model_instance, then doing some magic interceptions to gracefully handle shape and value transformations, to then output back the lora weights along with their names.

Copy link
Collaborator Author

@ngxson ngxson Jul 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 the model_instance, then split back into A and B, then it would allow all supported models to work with this.

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.

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.

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)

Copy link
Collaborator Author

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 added support_lora(), so model not overriding this method will not be able to convert lora.

Commit: ee2b35c

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sometimes it stacks them, sometimes it duplicates them, sometimes it permutes them, and sometimes it changes the values (like for Gemma's norms).

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:

  • We don't care if transformation is used on non-lora tensors like norm.weight ==> gemma should be ok to support
  • LlamaModel.permute(B)*A == LlamaModel.permute(B*A) at least observed on my tests (or maybe just coincident)
  • Scale BA*scale == (B*scale)*A

Copy link
Collaborator

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:

$ ./build/bin/llama-cli --log-disable -m /srv/LLMstash/tmp/stories_MOE-f16.gguf --temp 0 -p "Look in thy glass" -n 32
 Look in thy glass was a little girl. She was only three years old and she was three years old. She was three years old. She was three years old and she was
$ ./build/bin/llama-cli --log-disable -m /srv/LLMstash/tmp/stories_MOE-f16.gguf --temp 0 -p "Look in thy glass" -n 32 --lora /srv/LLMstash/tmp/lora_shakespeare_stories_MOE-f16.gguf
 Look in thy glass is a precious thing. They are so precious and can be held. They are made of glass, and they are not toys. They are made
$ ./build/bin/llama-cli --log-disable -m /srv/LLMstash/tmp/stories_MOE-f16.gguf --temp 0 -p "Look in thy glass" -n 128 --lora-scaled /srv/LLMstash/tmp/lora_shakespeare_stories_MOE-f16.gguf 2
 Look in thy glass in love of the eye:
That's when when the eye see thy on the sun's shining bright.
That's why those flowers look so bright,
But then thy in our glass's line,
Whose eye is red, then feasting on the other half,
When in their crows are red,
Whose eye is red, then on the so eye doth a side,
O in touching red thy a red eye doth a different,
And for my self I'll be a flower's sun's sun,
And for a red side

Copy link
Collaborator Author

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 scale the LoRA by 2

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.

Copy link
Collaborator

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.

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've added the alpha as training.lora.alpha to the GGUFs made by convert_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 of ggml_mul_mat where it made sense in 87301bd. Otherwise LoRA adapters for other architectures than llama were not really applied.

Copy link
Collaborator Author

@ngxson ngxson Jul 15, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perfect, thanks @compilade !

I did not store the rank (yet) because it can be taken from the tensor dimensions, but this can still be changed relatively easily.

After thinking more about it, I think we can add a kv training.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)

Copy link
Collaborator Author

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


# 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}")
4 changes: 2 additions & 2 deletions ggml/src/ggml.c
Original file line number Diff line number Diff line change
Expand Up @@ -19339,7 +19339,7 @@ void ggml_graph_dump_dot(const struct ggml_cgraph * gb, const struct ggml_cgraph

fprintf(fp, "digraph G {\n");
fprintf(fp, " newrank = true;\n");
fprintf(fp, " rankdir = LR;\n");
fprintf(fp, " rankdir = TB;\n");

for (int i = 0; i < gb->n_nodes; i++) {
struct ggml_tensor * node = gb->nodes[i];
Expand Down Expand Up @@ -19401,7 +19401,7 @@ void ggml_graph_dump_dot(const struct ggml_cgraph * gb, const struct ggml_cgraph
}

fprintf(fp, "CONST %d [%" PRId64 ", %" PRId64 "]", i, node->ne[0], node->ne[1]);
if (ggml_nelements(node) < 5) {
if (ggml_nelements(node) < 5 && node->data != NULL) {
fprintf(fp, " | (");
for (int j = 0; j < ggml_nelements(node); j++) {
if (node->type == GGML_TYPE_I8 || node->type == GGML_TYPE_I16 || node->type == GGML_TYPE_I32) {
Expand Down
37 changes: 25 additions & 12 deletions include/llama.h
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,9 @@ extern "C" {
const char * content;
} llama_chat_message;

// lora adapter
struct llama_lora_adapter;

// Helpers for getting default parameters
LLAMA_API struct llama_model_params llama_model_default_params(void);
LLAMA_API struct llama_context_params llama_context_default_params(void);
Expand Down Expand Up @@ -507,18 +510,28 @@ extern "C" {
const char * fname_out,
const llama_model_quantize_params * params);

// Apply a LoRA adapter to a loaded model
// path_base_model is the path to a higher quality model to use as a base for
// the layers modified by the adapter. Can be NULL to use the current loaded model.
// The model needs to be reloaded before applying a new adapter, otherwise the adapter
// will be applied on top of the previous one
// Returns 0 on success
LLAMA_API int32_t llama_model_apply_lora_from_file(
const struct llama_model * model,
const char * path_lora,
float scale,
const char * path_base_model,
int32_t n_threads);
// Load a LoRA adapter from file
// The loaded adapter will be associated to the given model, and will be free when the model is deleted
LLAMA_API struct llama_lora_adapter * llama_lora_adapter_init(
struct llama_model * model,
const char * path_lora);

// Add a loaded LoRA adapter to given context
// This will not modify model's weight
LLAMA_API int32_t llama_lora_adapter_set(
struct llama_context * ctx,
struct llama_lora_adapter * adapter,
float scale);

// Remove a LoRA adapter from given context
// Return -1 if the adapter is not present in the context
LLAMA_API int32_t llama_lora_adapter_remove(
struct llama_context * ctx,
struct llama_lora_adapter * adapter);

// Manually free a LoRA adapter
// Note: loaded adapters will be free when the associated model is deleted
LLAMA_API void llama_lora_adapter_free(struct llama_lora_adapter * adapter);

// Apply a loaded control vector to a llama_context, or if data is NULL, clear
// the currently loaded vector.
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@
-r ./requirements/requirements-convert_hf_to_gguf.txt
-r ./requirements/requirements-convert_hf_to_gguf_update.txt
-r ./requirements/requirements-convert_llama_ggml_to_gguf.txt
-r ./requirements/requirements-convert_lora_to_gguf.txt
2 changes: 2 additions & 0 deletions requirements/requirements-convert_lora_to_gguf.txt
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
Loading
Loading