| 319 | } |
| 320 | |
| 321 | static bool apply_lora(struct ggml_tensor * tensor, struct lora_data * lora, int n_threads) { |
| 322 | if (lora->ctx == NULL) { |
| 323 | return false; |
| 324 | } |
| 325 | std::string name = ggml_get_name(tensor); |
| 326 | std::string name_a = name + std::string(".loraA"); |
| 327 | std::string name_b = name + std::string(".loraB"); |
| 328 | struct ggml_tensor * lora_a = ggml_get_tensor(lora->ctx, name_a.c_str()); |
| 329 | struct ggml_tensor * lora_b = ggml_get_tensor(lora->ctx, name_b.c_str()); |
| 330 | if (lora_a == NULL || lora_b == NULL) { |
| 331 | return false; |
| 332 | } |
| 333 | |
| 334 | float scaling = lora->info.scale * (float)lora->lora_alpha / (float)lora->lora_r; |
| 335 | |
| 336 | struct ggml_init_params params; |
| 337 | params.mem_size = GGML_OBJECT_SIZE + ggml_graph_overhead() + ggml_tensor_overhead()*4 + GGML_MEM_ALIGN*5; |
| 338 | params.mem_buffer = NULL; |
| 339 | params.no_alloc = true; |
| 340 | struct ggml_context * ctx = NULL; |
| 341 | struct ggml_allocr * alloc = NULL; |
| 342 | struct ggml_cgraph * gf = NULL; |
| 343 | |
| 344 | ctx = ggml_init(params); |
| 345 | alloc = ggml_allocr_new_measure(tensor_alignment); |
| 346 | gf = build_graph_lora(ctx, tensor, lora_a, lora_b, scaling); |
| 347 | size_t alloc_size = ggml_allocr_alloc_graph(alloc, gf); |
| 348 | ggml_allocr_free(alloc); |
| 349 | ggml_free(ctx); |
| 350 | |
| 351 | static std::vector<uint8_t> data_compute; |
| 352 | data_compute.resize(alloc_size + tensor_alignment); |
| 353 | |
| 354 | ctx = ggml_init(params); |
| 355 | alloc = ggml_allocr_new(data_compute.data(), data_compute.size(), tensor_alignment); |
| 356 | gf = build_graph_lora(ctx, tensor, lora_a, lora_b, scaling); |
| 357 | ggml_allocr_alloc_graph(alloc, gf); |
| 358 | ggml_allocr_free(alloc); |
| 359 | |
| 360 | struct ggml_cplan cplan = ggml_graph_plan(gf, n_threads); |
| 361 | static std::vector<uint8_t> data_work; |
| 362 | data_work.resize(cplan.work_size); |
| 363 | cplan.work_data = data_work.data(); |
| 364 | |
| 365 | ggml_graph_compute(gf, &cplan); |
| 366 | |
| 367 | ggml_free(ctx); |
| 368 | return true; |
| 369 | } |
| 370 | |
| 371 | static void export_lora(struct export_lora_params * params) { |
| 372 | // load all loras |
no test coverage detected