09-lora.diff 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. diff --git a/common/common.cpp b/common/common.cpp
  2. index 2e8374d5..70d0afde 100644
  3. --- a/common/common.cpp
  4. +++ b/common/common.cpp
  5. @@ -2110,9 +2110,21 @@ struct llama_init_result llama_init_from_gpt_params(gpt_params & params) {
  6. loaded_la.adapter = llama_lora_adapter_init(model, la.path.c_str());
  7. if (loaded_la.adapter == nullptr) {
  8. fprintf(stderr, "%s: error: failed to apply lora adapter '%s'\n", __func__, la.path.c_str());
  9. - llama_free(lctx);
  10. - llama_free_model(model);
  11. - return iparams;
  12. +
  13. + // if that fails, try loading as ggla for compatibility
  14. + int err = llama_model_apply_lora_from_file(model,
  15. + la.path.c_str(),
  16. + la.scale,
  17. + nullptr,
  18. + params.n_threads);
  19. + if (err != 0) {
  20. + fprintf(stderr, "%s: error: failed to apply lora adapter\n", __func__);
  21. + llama_free(lctx);
  22. + llama_free_model(model);
  23. + return iparams;
  24. + } else {
  25. + break;
  26. + }
  27. }
  28. iparams.lora_adapters.push_back(loaded_la); // copy to list of loaded adapters
  29. }
  30. diff --git a/include/llama.h b/include/llama.h
  31. index 93fd77ca..b0fb37a6 100644
  32. --- a/include/llama.h
  33. +++ b/include/llama.h
  34. @@ -1160,6 +1160,20 @@ extern "C" {
  35. LLAMA_API void llama_dump_timing_info_yaml(FILE * stream, const struct llama_context * ctx);
  36. + // Apply a LoRA adapter to a loaded model
  37. + // path_base_model is the path to a higher quality model to use as a base for
  38. + // the layers modified by the adapter. Can be NULL to use the current loaded model.
  39. + // The model needs to be reloaded before applying a new adapter, otherwise the adapter
  40. + // will be applied on top of the previous one
  41. + // Returns 0 on success
  42. + LLAMA_API int32_t llama_model_apply_lora_from_file(
  43. + const struct llama_model * model,
  44. + const char * path_lora,
  45. + float scale,
  46. + const char * path_base_model,
  47. + int32_t n_threads);
  48. +
  49. +
  50. #ifdef __cplusplus
  51. }
  52. #endif
  53. diff --git a/src/llama.cpp b/src/llama.cpp
  54. index 80a0dd0f..9d7b0e17 100644
  55. --- a/src/llama.cpp
  56. +++ b/src/llama.cpp
  57. @@ -21880,3 +21880,290 @@ static void llama_log_callback_default(ggml_log_level level, const char * text,
  58. fputs(text, stderr);
  59. fflush(stderr);
  60. }
  61. +
  62. +static int llama_apply_lora_from_file_internal(
  63. + const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  64. +) {
  65. + LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  66. +
  67. + const int64_t t_start_lora_us = ggml_time_us();
  68. +
  69. + llama_file fin(path_lora, "rb");
  70. +
  71. + // verify magic and version
  72. + {
  73. + uint32_t magic = fin.read_u32();
  74. + if (magic != LLAMA_FILE_MAGIC_GGLA) {
  75. + LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  76. + return 1;
  77. + }
  78. +
  79. + uint32_t format_version = fin.read_u32();
  80. + if (format_version != 1) {
  81. + LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  82. + return 1;
  83. + }
  84. + }
  85. +
  86. + int32_t lora_r = fin.read_u32();
  87. + int32_t lora_alpha = fin.read_u32();
  88. + float scaling = scale * (float)lora_alpha / (float)lora_r;
  89. +
  90. + LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  91. +
  92. + // load base model
  93. + std::unique_ptr<llama_model_loader> ml;
  94. + if (path_base_model) {
  95. + LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  96. + ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*check_tensors*/ false, /*kv_overrides*/ nullptr));
  97. + ml->init_mappings(/*prefetch*/ false); // no prefetching
  98. + }
  99. +
  100. + struct tensor_meta {
  101. + std::string name;
  102. + ggml_type type;
  103. + int32_t ne[2];
  104. + size_t offset;
  105. + };
  106. + std::map<std::string, tensor_meta> tensor_meta_map;
  107. +
  108. + // load all tensor meta
  109. + while (true) {
  110. + if (fin.tell() == fin.size) {
  111. + // eof
  112. + break;
  113. + }
  114. +
  115. + int32_t n_dims;
  116. + int32_t name_len;
  117. + int32_t ftype;
  118. +
  119. + fin.read_raw(&n_dims, sizeof(n_dims));
  120. + fin.read_raw(&name_len, sizeof(name_len));
  121. + fin.read_raw(&ftype, sizeof(ftype));
  122. +
  123. + if (n_dims != 1 && n_dims != 2) {
  124. + LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  125. + return 1;
  126. + }
  127. +
  128. + int32_t ne[2] = { 1, 1 };
  129. + for (int i = 0; i < n_dims; ++i) {
  130. + fin.read_raw(&ne[i], sizeof(ne[i]));
  131. + }
  132. +
  133. + std::string name;
  134. + {
  135. + GGML_ASSERT(name_len < GGML_MAX_NAME);
  136. + char buf[GGML_MAX_NAME];
  137. + fin.read_raw(buf, name_len);
  138. + name = std::string(buf, name_len);
  139. + }
  140. +
  141. + // check for lora suffix
  142. + std::string lora_suffix;
  143. + if (name.length() > 6) {
  144. + lora_suffix = name.substr(name.length() - 6);
  145. + }
  146. + if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  147. + LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  148. + return 1;
  149. + }
  150. +
  151. + // tensor type
  152. + ggml_type wtype;
  153. + switch (ftype) {
  154. + case 0: wtype = GGML_TYPE_F32; break;
  155. + case 1: wtype = GGML_TYPE_F16; break;
  156. + default:
  157. + {
  158. + LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  159. + __func__, ftype);
  160. + return 1;
  161. + }
  162. + }
  163. +
  164. + // data offset
  165. + size_t offset = fin.tell();
  166. + offset = (offset + 31) & -32;
  167. +
  168. + // skip tensor data
  169. + fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  170. +
  171. + tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  172. + }
  173. +
  174. + bool warned = false;
  175. + int n_tensors = 0;
  176. +
  177. + // apply
  178. + ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  179. + if (backend_cpu == nullptr) {
  180. + LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  181. + return 1;
  182. + }
  183. + ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  184. +
  185. + std::vector<no_init<uint8_t>> read_buf;
  186. + for (const auto & it : model.tensors_by_name) {
  187. + const std::string & base_name = it.first;
  188. + ggml_tensor * model_t = it.second;
  189. +
  190. + if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  191. + tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  192. + continue;
  193. + }
  194. +
  195. + tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  196. + tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  197. +
  198. + ggml_init_params lora_init_params = {
  199. + /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  200. + /* .mem_buffer */ nullptr,
  201. + /* .no_alloc */ true,
  202. + };
  203. + ggml_context * lora_ctx = ggml_init(lora_init_params);
  204. + if (lora_ctx == nullptr) {
  205. + LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  206. + ggml_backend_free(backend_cpu);
  207. + return 1;
  208. + }
  209. +
  210. + // create tensors
  211. + ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  212. + ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  213. + ggml_set_name(loraA, metaA.name.c_str());
  214. + ggml_set_name(loraB, metaB.name.c_str());
  215. +
  216. + ggml_tensor * base_t;
  217. + if (ml) {
  218. + if (!ml->get_tensor_meta(base_name.c_str())) {
  219. + LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  220. + return 1;
  221. + }
  222. + base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  223. + } else {
  224. + base_t = ggml_dup_tensor(lora_ctx, model_t);
  225. + }
  226. + ggml_set_name(base_t, base_name.c_str());
  227. +
  228. + // allocate in backend buffer
  229. + ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  230. + if (lora_buf == nullptr) {
  231. + LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  232. + return 1;
  233. + }
  234. +
  235. + // load tensor data
  236. + auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  237. + read_buf.resize(ggml_nbytes(tensor));
  238. + fin.seek(tensor_meta.offset, SEEK_SET);
  239. + fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  240. + ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  241. + };
  242. + load_tensor(metaA, loraA);
  243. + load_tensor(metaB, loraB);
  244. +
  245. + // load base model tensor data
  246. + if (ml) {
  247. + ml->load_data_for(base_t);
  248. + } else {
  249. + ggml_backend_tensor_copy(model_t, base_t);
  250. + }
  251. +
  252. + if (ggml_is_quantized(base_t->type) && !warned) {
  253. + LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  254. + "use a f16 or f32 base model with --lora-base\n", __func__);
  255. + warned = true;
  256. + }
  257. +
  258. + if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  259. + LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  260. + " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  261. + ggml_free(lora_ctx);
  262. + ggml_backend_buffer_free(lora_buf);
  263. + ggml_backend_free(backend_cpu);
  264. + return 1;
  265. + }
  266. +
  267. + auto build_lora_graph = [&]() {
  268. + // w = w + BA*s
  269. + ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  270. + ggml_set_name(BA, "BA");
  271. +
  272. + if (scaling != 1.0f) {
  273. + BA = ggml_scale(lora_ctx, BA, scaling);
  274. + ggml_set_name(BA, "BA_scaled");
  275. + }
  276. +
  277. + ggml_tensor * r;
  278. + r = ggml_add_inplace(lora_ctx, base_t, BA);
  279. + ggml_set_name(r, "r_add");
  280. +
  281. + if (base_t->type != model_t->type) {
  282. + // convert the result to the model type
  283. + r = ggml_cast(lora_ctx, r, model_t->type);
  284. + ggml_set_name(r, "r_cast");
  285. + }
  286. +
  287. + return r;
  288. + };
  289. +
  290. + ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  291. + ggml_tensor * r = build_lora_graph();
  292. + ggml_build_forward_expand(gf, r);
  293. +
  294. + ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  295. + if (graph_buf == nullptr) {
  296. + LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  297. + ggml_free(lora_ctx);
  298. + ggml_backend_buffer_free(lora_buf);
  299. + ggml_backend_free(backend_cpu);
  300. + return 1;
  301. + }
  302. +
  303. + ggml_backend_graph_compute(backend_cpu, gf);
  304. +
  305. + ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  306. +
  307. +#if 0
  308. + // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  309. + //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  310. +
  311. + // sched compute
  312. + ggml_build_forward_expand(gf, build_graph());
  313. + ggml_backend_sched_init_measure(sched, gf);
  314. +
  315. + // create the graph again, since the previous one was destroyed by the measure
  316. + ggml_graph_clear(gf);
  317. + ggml_build_forward_expand(gf, build_graph());
  318. + ggml_backend_sched_graph_compute(sched, gf);
  319. + ggml_backend_sched_free(sched);
  320. +#endif
  321. +
  322. + ggml_backend_buffer_free(lora_buf);
  323. + ggml_backend_buffer_free(graph_buf);
  324. + ggml_free(lora_ctx);
  325. +
  326. + n_tensors++;
  327. + if (n_tensors % 4 == 0) {
  328. + LLAMA_LOG_INFO(".");
  329. + }
  330. + }
  331. +
  332. + ggml_backend_free(backend_cpu);
  333. +
  334. + const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  335. + LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  336. +
  337. + return 0;
  338. +}
  339. +
  340. +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) {
  341. + try {
  342. + return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  343. + } catch (const std::exception & err) {
  344. + LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  345. + return 1;
  346. + }
  347. +}
  348. \ No newline at end of file