Skip to content

Commit 93fbfd0

Browse files
committed
(wip) support mergekit-extracted lora
1 parent dc7cef9 commit 93fbfd0

File tree

4 files changed

+102
-6
lines changed

4 files changed

+102
-6
lines changed

convert_lora_to_gguf.py

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,9 @@ def get_base_tensor_name(lora_tensor_name: str) -> str:
226226
base_name = lora_tensor_name.replace("base_model.model.", "")
227227
base_name = base_name.replace(".lora_A.weight", ".weight")
228228
base_name = base_name.replace(".lora_B.weight", ".weight")
229+
# models produced by mergekit-extract-lora have token embeddings in the adapter
230+
base_name = base_name.replace(".lora_embedding_A", ".weight")
231+
base_name = base_name.replace(".lora_embedding_B", ".weight")
229232
return base_name
230233

231234

@@ -260,6 +263,10 @@ def parse_args() -> argparse.Namespace:
260263
"--base", type=Path,
261264
help="directory containing Hugging Face model config files (config.json, tokenizer.json) for the base model that the adapter is based on - only config is needed, actual model weights are not required. If base model is unspecified, it will be loaded from Hugging Face hub based on the adapter config",
262265
)
266+
parser.add_argument(
267+
"--base-model-id", type=str,
268+
help="the model ID of the base model, if it is not available locally or in the adapter config. If specified, it will ignore --base and load the base model config from the Hugging Face hub (Example: 'meta-llama/Llama-3.2-1B-Instruct')",
269+
)
263270
parser.add_argument(
264271
"lora_path", type=Path,
265272
help="directory containing Hugging Face PEFT LoRA config (adapter_model.json) and weights (adapter_model.safetensors or adapter_model.bin)",
@@ -290,6 +297,7 @@ def load_hparams_from_hf(hf_model_id: str) -> dict[str, Any]:
290297

291298
dir_base_model: Path | None = args.base
292299
dir_lora: Path = args.lora_path
300+
base_model_id: str | None = args.base_model_id
293301
lora_config = dir_lora / "adapter_config.json"
294302
input_model = dir_lora / "adapter_model.safetensors"
295303

@@ -313,7 +321,10 @@ def load_hparams_from_hf(hf_model_id: str) -> dict[str, Any]:
313321
lparams: dict[str, Any] = json.load(f)
314322

315323
# load base model
316-
if dir_base_model is None:
324+
if base_model_id is not None:
325+
logger.info(f"Loading base model from Hugging Face: {base_model_id}")
326+
hparams = load_hparams_from_hf(base_model_id)
327+
elif dir_base_model is None:
317328
if "base_model_name_or_path" in lparams:
318329
model_id = lparams["base_model_name_or_path"]
319330
logger.info(f"Loading base model from Hugging Face: {model_id}")
@@ -371,17 +382,26 @@ def get_tensors(self) -> Iterator[tuple[str, Tensor]]:
371382
if self.lazy:
372383
tensor = LazyTorchTensor.from_eager(tensor)
373384
base_name = get_base_tensor_name(name)
374-
is_lora_a = ".lora_A.weight" in name
375-
is_lora_b = ".lora_B.weight" in name
385+
# note: lora_embedding is transposed by mergekit-extract-lora, so it's reversed here
386+
is_lora_a = ".lora_A.weight" in name or ".lora_embedding_B" in name
387+
is_lora_b = ".lora_B.weight" in name or ".lora_embedding_A" in name
376388
if not is_lora_a and not is_lora_b:
377389
if ".base_layer.weight" in name:
378390
continue
391+
# mergekit-extract-lora add these layernorm to the adapter
392+
if ".layernorm" or ".norm" in name:
393+
yield (base_name, tensor)
394+
continue
379395
logger.error(f"Unexpected name '{name}': Not a lora_A or lora_B tensor")
380396
if ".embed_tokens.weight" in name or ".lm_head.weight" in name:
381397
logger.error("Embeddings is present in the adapter. This can be due to new tokens added during fine tuning")
382398
logger.error("Please refer to https://github.com/ggerganov/llama.cpp/pull/9948")
383399
sys.exit(1)
384400

401+
# mergekit-extract-lora transposes this tensor, we need to transpose it back
402+
if ".lora_embedding" in name:
403+
tensor = tensor.T
404+
385405
if base_name in tensor_map:
386406
if is_lora_a:
387407
tensor_map[base_name].A = tensor
@@ -407,6 +427,13 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter
407427
if name == "lm_head.weight" and len(dest) == 0:
408428
raise ValueError("lm_head is present in adapter, but is ignored in base model")
409429
for dest_name, dest_data in dest:
430+
# mergekit-extract-lora add these layernorm to the adapter
431+
if "_norm" in dest_name:
432+
assert dest_data.dim() == 1
433+
yield (dest_name, dest_data)
434+
continue
435+
436+
# otherwise, we must get the lora_A and lora_B tensors
410437
assert isinstance(dest_data, LoraTorchTensor)
411438
lora_a, lora_b = dest_data.get_lora_A_B()
412439

src/llama-adapter.cpp

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,9 @@ static void llama_lora_adapter_init_impl(struct llama_model & model, const char
242242
} else {
243243
ab_map[name].b = cur;
244244
}
245+
} else if (str_endswith(name, "_norm.weight")) {
246+
// norm only has 1 dim, so tensor b == nullptr
247+
ab_map[name] = llama_lora_weight(cur);
245248
} else {
246249
throw std::runtime_error("LoRA tensor '" + name + "' has unexpected suffix");
247250
}
@@ -251,6 +254,9 @@ static void llama_lora_adapter_init_impl(struct llama_model & model, const char
251254
for (auto & it : ab_map) {
252255
const std::string & name = it.first;
253256
llama_lora_weight & w = it.second;
257+
if (w.is_norm) {
258+
continue;
259+
}
254260

255261
if (!w.a || !w.b) {
256262
throw std::runtime_error("LoRA tensor pair for '" + name + "' is missing one component");
@@ -279,6 +285,24 @@ static void llama_lora_adapter_init_impl(struct llama_model & model, const char
279285
adapter.ab_map[name] = llama_lora_weight(tensor_a, tensor_b);
280286
}
281287

288+
// add norm vectors
289+
for (auto & it : ab_map) {
290+
const std::string & name = it.first;
291+
llama_lora_weight & w = it.second;
292+
if (w.is_norm) {
293+
GGML_ASSERT(w.a != nullptr);
294+
// device buft and device ctx
295+
auto * model_tensor = llama_model_get_tensor(model, name.c_str());
296+
if (!model_tensor) {
297+
throw std::runtime_error("LoRA tensor '" + name + "' does not exist in base model");
298+
}
299+
struct ggml_context * dev_ctx = ctx_for_buft(ggml_backend_buffer_get_type(model_tensor->buffer));
300+
struct ggml_tensor * tensor_norm = ggml_dup_tensor(dev_ctx, w.a);
301+
ggml_set_name(tensor_norm, w.a->name);
302+
adapter.ab_map[it.first] = llama_lora_weight(tensor_norm);
303+
}
304+
}
305+
282306
// allocate tensors / buffers and zero
283307
{
284308
adapter.ctxs.reserve(ctx_map.size());
@@ -311,7 +335,9 @@ static void llama_lora_adapter_init_impl(struct llama_model & model, const char
311335
auto orig = ab_map[it.first];
312336
auto dev = it.second;
313337
set_tensor(orig.a, dev.a);
314-
set_tensor(orig.b, dev.b);
338+
if (!dev.is_norm) {
339+
set_tensor(orig.b, dev.b);
340+
}
315341
}
316342
}
317343

src/llama-adapter.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,11 @@ struct llama_lora_weight {
4545
struct ggml_tensor * a = nullptr;
4646
struct ggml_tensor * b = nullptr;
4747

48+
// note: norm only has 1 dim, so tensor b == nullptr
49+
bool is_norm = false; // is this a norm vector? (e.g. _norm.weight)
50+
4851
llama_lora_weight() = default;
52+
llama_lora_weight(struct ggml_tensor * a) : a(a), is_norm(true) {}
4953
llama_lora_weight(struct ggml_tensor * a, struct ggml_tensor * b) : a(a), b(b) {}
5054
};
5155

src/llama.cpp

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2545,6 +2545,28 @@ static struct ggml_tensor * llm_build_inp_embd(
25452545
ggml_set_input(lctx.inp_tokens);
25462546

25472547
inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
2548+
//printf("tok_embd shape: %d x %d\n", tok_embd->ne[0], tok_embd->ne[1]);
2549+
//printf("inpL shape: %d x %d\n", inpL->ne[0], inpL->ne[1]);
2550+
2551+
// apply lora for embedding tokens if needed
2552+
for (auto & it : lctx.lora_adapters) {
2553+
struct llama_lora_weight * lora = it.first->get_weight(tok_embd);
2554+
if (lora == nullptr) {
2555+
continue;
2556+
}
2557+
const float alpha = it.first->alpha;
2558+
const float rank = (float) lora->b->ne[0];
2559+
const float scale = alpha ? it.second * alpha / rank : it.second;
2560+
auto ss = ggml_get_rows(ctx, lora->b, lctx.inp_tokens);
2561+
//printf("a shape: %d x %d\n", lora->a->ne[0], lora->a->ne[1]);
2562+
//printf("b shape: %d x %d\n", lora->b->ne[0], lora->b->ne[1]);
2563+
//printf("ss shape: %d x %d\n", ss->ne[0], ss->ne[1]);
2564+
struct ggml_tensor * inpL_delta = ggml_scale(ctx, ggml_mul_mat(
2565+
ctx, ss, ggml_transpose(ctx, lora->a)
2566+
), scale);
2567+
//printf("inpL_delta shape: %d x %d\n", inpL_delta->ne[0], inpL_delta->ne[1]);
2568+
inpL = ggml_add(ctx, inpL, ggml_cont(ctx, ggml_transpose(ctx, inpL_delta)));
2569+
}
25482570
} else {
25492571
lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, ubatch.n_tokens);
25502572
inpL = lctx.inp_embd;
@@ -3897,9 +3919,17 @@ struct llm_build_context {
38973919
for (int il = 0; il < n_layer; ++il) {
38983920
struct ggml_tensor * inpSA = inpL;
38993921

3922+
struct ggml_tensor * attn_norm = model.layers[il].attn_norm;
3923+
for (auto & it : lctx.lora_adapters) {
3924+
struct llama_lora_weight * lora = it.first->get_weight(model.layers[il].attn_norm);
3925+
if (lora && lora->is_norm) {
3926+
attn_norm = ggml_add(ctx0, attn_norm, ggml_scale(ctx0, lora->a, 0.5));
3927+
}
3928+
}
3929+
39003930
// norm
39013931
cur = llm_build_norm(ctx0, inpL, hparams,
3902-
model.layers[il].attn_norm, NULL,
3932+
attn_norm, NULL,
39033933
LLM_NORM_RMS, cb, il);
39043934
cb(cur, "attn_norm", il);
39053935

@@ -3967,8 +3997,17 @@ struct llm_build_context {
39673997

39683998
// feed-forward network
39693999
if (model.layers[il].ffn_gate_inp == nullptr) {
4000+
4001+
struct ggml_tensor * ffn_norm = model.layers[il].ffn_norm;
4002+
// for (auto & it : lctx.lora_adapters) {
4003+
// struct llama_lora_weight * lora = it.first->get_weight(ffn_norm);
4004+
// if (lora && lora->is_norm) {
4005+
// ffn_norm = ggml_add(ctx0, ffn_norm, lora->a);
4006+
// }
4007+
// }
4008+
39704009
cur = llm_build_norm(ctx0, ffn_inp, hparams,
3971-
model.layers[il].ffn_norm, NULL,
4010+
ffn_norm, NULL,
39724011
LLM_NORM_RMS, cb, il);
39734012
cb(cur, "ffn_norm", il);
39744013

0 commit comments

Comments
 (0)