export-lora.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. #include "common.h"
  2. #include "ggml.h"
  3. #include "ggml-alloc.h"
  4. #include <map>
  5. #include <vector>
  6. #include <string>
  7. #include <thread>
  8. #include <fstream>
  9. static bool g_verbose = false;
  10. struct tensor_transformation {
  11. struct ggml_tensor * in;
  12. struct ggml_tensor * out;
  13. bool is_copy;
  14. };
  15. static std::string get_kv_str(struct gguf_context * ctx_gguf, const std::string & key){
  16. int id = gguf_find_key(ctx_gguf, key.c_str());
  17. return id < 0 ? "" : std::string(gguf_get_val_str(ctx_gguf, id));
  18. }
  19. static float get_kv_f32(struct gguf_context * ctx_gguf, const std::string & key) {
  20. int id = gguf_find_key(ctx_gguf, key.c_str());
  21. return id < 0 ? 0.0f : gguf_get_val_f32(ctx_gguf, id);
  22. }
  23. static void zeros(std::ofstream & file, size_t n) {
  24. char zero = 0;
  25. for (size_t i = 0; i < n; ++i) {
  26. file.write(&zero, 1);
  27. }
  28. }
  29. static std::string ggml_ne_string(const ggml_tensor * t) {
  30. std::string str;
  31. for (int i = 0; i < GGML_MAX_DIMS; ++i) {
  32. str += std::to_string(t->ne[i]);
  33. if (i + 1 < GGML_MAX_DIMS) {
  34. str += ", ";
  35. }
  36. }
  37. return str;
  38. }
  39. static struct gguf_context * load_gguf(std::string & fname, struct ggml_context ** ctx_ggml) {
  40. struct gguf_init_params params = {
  41. /*.no_alloc = */ true,
  42. /*.ctx = */ ctx_ggml,
  43. };
  44. struct gguf_context * ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  45. if (!ctx_gguf) {
  46. throw std::runtime_error("failed to load input GGUF from " + fname);
  47. }
  48. return ctx_gguf;
  49. }
  50. struct file_input {
  51. struct ggml_context * ctx_meta = nullptr;
  52. struct gguf_context * ctx_gguf = nullptr;
  53. std::ifstream f_in;
  54. std::map<std::string, ggml_tensor *> tensors;
  55. float alpha;
  56. float scale;
  57. file_input(std::string & fname, float scale): f_in(fname, std::ios::binary), scale(scale) {
  58. if (!f_in.is_open()) {
  59. throw std::runtime_error("failed to open input gguf from " + fname);
  60. }
  61. ctx_gguf = load_gguf(fname, &ctx_meta);
  62. alpha = get_kv_f32(ctx_gguf, "adapter.lora.alpha");
  63. printf("%s: loaded gguf from %s\n", __func__, fname.c_str());
  64. for (ggml_tensor * cur = ggml_get_first_tensor(ctx_meta); cur; cur = ggml_get_next_tensor(ctx_meta, cur)) {
  65. std::string name(cur->name);
  66. tensors[name] = cur;
  67. if (g_verbose) {
  68. printf("%s: %s\n", __func__, cur->name);
  69. }
  70. }
  71. }
  72. ggml_tensor * get_tensor(std::string name) {
  73. if (tensors.find(name) == tensors.end()) {
  74. return nullptr;
  75. }
  76. return tensors[name];
  77. }
  78. void read_tensor_data(std::string name, std::vector<uint8_t> & buf) {
  79. if (tensors.find(name) == tensors.end()) {
  80. throw std::runtime_error("cannot find tensor with name: " + name);
  81. }
  82. auto len = ggml_nbytes(tensors[name]);
  83. if (buf.size() < len) {
  84. buf.resize(len);
  85. }
  86. auto i_tensor_in = gguf_find_tensor(ctx_gguf, name.c_str()); // idx of tensor in the input file
  87. auto offset = gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, i_tensor_in);
  88. f_in.seekg(offset);
  89. f_in.read((char* )buf.data(), len);
  90. }
  91. ~file_input() {
  92. gguf_free(ctx_gguf);
  93. ggml_free(ctx_meta);
  94. }
  95. };
  96. struct lora_merge_ctx {
  97. // input base model + adapters
  98. file_input base_model;
  99. std::vector<std::unique_ptr<file_input>> adapters;
  100. // for computing merged tensor
  101. int n_threads;
  102. ggml_backend_t backend = nullptr;
  103. ggml_gallocr_t allocr = nullptr;
  104. std::vector<uint8_t> read_buf;
  105. // output file
  106. struct gguf_context * ctx_out;
  107. struct ggml_context * ctx_out_ggml;
  108. std::ofstream fout;
  109. lora_merge_ctx(
  110. std::string & base_fname,
  111. std::vector<llama_lora_adapter_info> & lora_files,
  112. std::string & outfile,
  113. int n_threads) : base_model(base_fname, 0), n_threads(n_threads), fout(outfile, std::ios::binary) {
  114. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  115. if (gguf_find_key(base_model.ctx_gguf, LLM_KV_SPLIT_COUNT) >= 0) {
  116. throw std::runtime_error("split model is not yet supported");
  117. }
  118. for (auto & lora_inp : lora_files) {
  119. auto fname = lora_inp.path;
  120. auto scale = lora_inp.scale;
  121. std::unique_ptr<file_input> adapter(new file_input(fname, scale));
  122. check_metadata_lora(adapter.get());
  123. adapters.push_back(std::move(adapter));
  124. }
  125. ctx_out = gguf_init_empty();
  126. struct ggml_init_params params = {
  127. /*.mem_size =*/ gguf_get_n_tensors(base_model.ctx_gguf)*ggml_tensor_overhead(),
  128. /*.mem_buffer =*/ NULL,
  129. /*.no_alloc =*/ true,
  130. };
  131. ctx_out_ggml = ggml_init(params);
  132. backend = ggml_backend_cpu_init();
  133. allocr = ggml_gallocr_new(ggml_backend_get_default_buffer_type(backend));
  134. }
  135. void check_metadata_lora(file_input * adapter) {
  136. auto general_type = get_kv_str(adapter->ctx_gguf, "general.type");
  137. if (general_type != "adapter") {
  138. throw std::runtime_error("expect general.type to be 'adapter', but got: " + general_type);
  139. }
  140. auto adapter_type = get_kv_str(adapter->ctx_gguf, "adapter.type");
  141. if (adapter_type != "lora") {
  142. throw std::runtime_error("expect adapter.type to be 'lora', but got: " + adapter_type);
  143. }
  144. auto general_arch_base = get_kv_str(base_model.ctx_gguf, "general.architecture");
  145. auto general_arch_lora = get_kv_str(adapter->ctx_gguf, "general.architecture");
  146. if (general_arch_base != general_arch_lora) {
  147. throw std::runtime_error("model arch and LoRA arch mismatch");
  148. }
  149. }
  150. ggml_type get_out_tensor_type(struct ggml_tensor * t) {
  151. if (t->type == GGML_TYPE_F32) {
  152. return GGML_TYPE_F32;
  153. } else {
  154. return GGML_TYPE_F16;
  155. }
  156. }
  157. void run_merge() {
  158. // prepare metadata
  159. gguf_set_kv(ctx_out, base_model.ctx_gguf);
  160. // output is forced to f16 for now
  161. gguf_set_val_u32(ctx_out, "general.file_type", LLAMA_FTYPE_MOSTLY_F16);
  162. // check if all lora adapters have the same tensors
  163. // TODO: remove this when we can support merging subset of adapters. Ref: https://github.com/ggerganov/llama.cpp/pull/8607#discussion_r1686027777
  164. static const char * err_no_subset_adapter = "Input adapters do not have the same list of tensors. This is not yet supported. Please merge the adapter one-by-one instead of merging all at once.";
  165. if (adapters.size() > 1) {
  166. for (size_t i = 1; i < adapters.size(); ++i) {
  167. if (adapters[0]->tensors.size() != adapters[i]->tensors.size()) {
  168. throw std::runtime_error(err_no_subset_adapter);
  169. }
  170. for (auto & it : adapters[i]->tensors) {
  171. if (adapters[0]->get_tensor(it.first) == nullptr) {
  172. throw std::runtime_error(err_no_subset_adapter);
  173. }
  174. }
  175. }
  176. }
  177. // mapping base tensor to out tensor (same shape with base, but different type)
  178. std::vector<tensor_transformation> trans;
  179. for (auto & it : base_model.tensors) {
  180. bool t_a = true;
  181. bool t_b = true;
  182. for (auto & adapter : adapters) {
  183. t_a &= nullptr != adapter->get_tensor(it.first + ".lora_a");
  184. t_b &= nullptr != adapter->get_tensor(it.first + ".lora_b");
  185. }
  186. auto base_tensor = it.second;
  187. if (!t_a && !t_b) {
  188. // only copy
  189. struct ggml_tensor * cpy_tensor = ggml_dup_tensor(ctx_out_ggml, base_tensor);
  190. ggml_set_name(cpy_tensor, base_tensor->name);
  191. trans.push_back({
  192. cpy_tensor,
  193. cpy_tensor,
  194. true,
  195. });
  196. gguf_add_tensor(ctx_out, cpy_tensor);
  197. } else if (t_a && t_b) {
  198. // need merging
  199. struct ggml_tensor * out_tensor = ggml_new_tensor(
  200. ctx_out_ggml, get_out_tensor_type(base_tensor), GGML_MAX_DIMS, base_tensor->ne);
  201. ggml_set_name(out_tensor, base_tensor->name);
  202. trans.push_back({
  203. base_tensor,
  204. out_tensor,
  205. false,
  206. });
  207. gguf_add_tensor(ctx_out, out_tensor);
  208. } else {
  209. throw std::runtime_error("tensor " + it.first + " missing either lora_a or lora_b");
  210. }
  211. }
  212. // placeholder for the meta data
  213. {
  214. size_t meta_size = gguf_get_meta_size(ctx_out);
  215. zeros(fout, meta_size);
  216. }
  217. // process base model tensors
  218. size_t n_merged = 0;
  219. for (auto & it : trans) {
  220. if (!it.is_copy) {
  221. merge_tensor(it.in, it.out);
  222. n_merged++;
  223. } else {
  224. copy_tensor(it.in);
  225. }
  226. }
  227. // write output metadata
  228. {
  229. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  230. gguf_get_meta_data(ctx_out, data.data());
  231. fout.seekp(0);
  232. fout.write((const char *)data.data(), data.size());
  233. }
  234. printf("%s : merged %ld tensors with lora adapters\n", __func__, n_merged);
  235. printf("%s : wrote %ld tensors to output file\n", __func__, trans.size());
  236. }
  237. void copy_tensor(struct ggml_tensor * base) {
  238. printf("%s : %s [%s]\n", __func__, base->name, ggml_ne_string(base).c_str());
  239. size_t len = ggml_nbytes(base);
  240. base_model.read_tensor_data(base->name, read_buf);
  241. fout.write((char* )read_buf.data(), len);
  242. zeros(fout, GGML_PAD(len, GGUF_DEFAULT_ALIGNMENT) - len);
  243. }
  244. void merge_tensor(struct ggml_tensor * base, struct ggml_tensor * out) {
  245. std::string name_base(base->name);
  246. std::string name_lora_a = name_base + ".lora_a";
  247. std::string name_lora_b = name_base + ".lora_b";
  248. printf("%s : %s [%s]\n", __func__, base->name, ggml_ne_string(base).c_str());
  249. // context for input tensor
  250. std::vector<struct ggml_tensor *> inp_a(adapters.size());
  251. std::vector<struct ggml_tensor *> inp_b(adapters.size());
  252. struct ggml_init_params params {
  253. /*.mem_size =*/ ggml_tensor_overhead()*(2+adapters.size()*2),
  254. /*.mem_buffer =*/ NULL,
  255. /*.no_alloc =*/ true,
  256. };
  257. struct ggml_context * ctx = ggml_init(params);
  258. // alloc tensors
  259. struct ggml_tensor * inp_base = ggml_new_tensor(ctx, GGML_TYPE_F32, GGML_MAX_DIMS, base->ne);
  260. for (size_t i = 0; i < adapters.size(); ++i) {
  261. auto t_a = adapters[i]->get_tensor(name_lora_a);
  262. auto t_b = adapters[i]->get_tensor(name_lora_b);
  263. // TODO: add support for quantized lora
  264. if (ggml_is_quantized(t_a->type) || ggml_is_quantized(t_b->type)) {
  265. throw std::runtime_error("quantized LoRA adapters is not supported, please retry with f16 or f32");
  266. }
  267. inp_a[i] = ggml_dup_tensor(ctx, t_a);
  268. inp_b[i] = ggml_dup_tensor(ctx, t_b);
  269. }
  270. ggml_backend_buffer_t buffer = ggml_backend_alloc_ctx_tensors(ctx, backend);
  271. // load base tensor to backend buffer
  272. base_model.read_tensor_data(name_base, read_buf);
  273. if (base->type != GGML_TYPE_F32) {
  274. // optionally dequantize it
  275. printf("%s : + dequantize base tensor from %s to F32\n", __func__, ggml_type_name(base->type));
  276. auto nels = ggml_nelements(inp_base);
  277. ggml_type_traits_t qtype = ggml_internal_get_type_traits(base->type);
  278. std::vector<uint8_t> dequant_buf(nels * sizeof(float));
  279. qtype.to_float(read_buf.data(), (float *)dequant_buf.data(), nels);
  280. ggml_backend_tensor_set(inp_base, dequant_buf.data(), 0, dequant_buf.size());
  281. } else {
  282. ggml_backend_tensor_set(inp_base, read_buf.data(), 0, ggml_nbytes(inp_base));
  283. }
  284. // load lora tensors to backend buffer
  285. for (size_t i = 0; i < adapters.size(); ++i) {
  286. adapters[i]->read_tensor_data(name_lora_a, read_buf);
  287. ggml_backend_tensor_set(inp_a[i], read_buf.data(), 0, ggml_nbytes(inp_a[i]));
  288. adapters[i]->read_tensor_data(name_lora_b, read_buf);
  289. ggml_backend_tensor_set(inp_b[i], read_buf.data(), 0, ggml_nbytes(inp_b[i]));
  290. }
  291. // build graph
  292. struct ggml_cgraph * gf;
  293. {
  294. static size_t buf_size = ggml_tensor_overhead()*GGML_DEFAULT_GRAPH_SIZE + ggml_graph_overhead();
  295. static std::vector<uint8_t> buf(buf_size);
  296. struct ggml_init_params params0 = {
  297. /*.mem_size =*/ buf_size,
  298. /*.mem_buffer =*/ buf.data(),
  299. /*.no_alloc =*/ true,
  300. };
  301. struct ggml_context * ctx0 = ggml_init(params0);
  302. gf = ggml_new_graph(ctx0);
  303. struct ggml_tensor * cur = inp_base;
  304. for (size_t i = 0; i < adapters.size(); ++i) {
  305. struct ggml_tensor * a_T = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_cast(ctx0, inp_a[i], GGML_TYPE_F32)));
  306. struct ggml_tensor * delta = ggml_mul_mat(ctx0, a_T, ggml_cast(ctx0, inp_b[i], GGML_TYPE_F32));
  307. // scale
  308. const float alpha = adapters[i]->alpha;
  309. const float rank = (float) inp_b[i]->ne[0];
  310. const float scale = alpha ? adapters[i]->scale * alpha / rank : adapters[i]->scale;
  311. delta = ggml_scale(ctx0, delta, scale);
  312. cur = ggml_add(ctx0, delta, cur);
  313. printf("%s : + merging from adapter[%ld] type=%s\n", __func__, i, ggml_type_name(inp_a[i]->type));
  314. printf("%s : input_scale=%f calculated_scale=%f rank=%d\n", __func__, adapters[i]->scale, scale, (int) inp_b[i]->ne[0]);
  315. }
  316. cur = ggml_cast(ctx0, cur, out->type);
  317. printf("%s : + output type is %s\n", __func__, ggml_type_name(out->type));
  318. ggml_build_forward_expand(gf, cur);
  319. ggml_free(ctx0);
  320. }
  321. // compute
  322. {
  323. ggml_gallocr_alloc_graph(allocr, gf);
  324. ggml_backend_cpu_set_n_threads(backend, n_threads);
  325. ggml_backend_graph_compute(backend, gf);
  326. }
  327. // write data to output file
  328. {
  329. auto result = gf->nodes[gf->n_nodes - 1];
  330. size_t len = ggml_nbytes(result);
  331. if (read_buf.size() < len) {
  332. read_buf.resize(len);
  333. }
  334. ggml_backend_tensor_get(result, read_buf.data(), 0, len);
  335. fout.write((char* )read_buf.data(), len);
  336. zeros(fout, GGML_PAD(len, GGUF_DEFAULT_ALIGNMENT) - len);
  337. }
  338. ggml_free(ctx);
  339. ggml_backend_buffer_free(buffer);
  340. }
  341. ~lora_merge_ctx() {
  342. ggml_gallocr_free(allocr);
  343. ggml_backend_free(backend);
  344. gguf_free(ctx_out);
  345. ggml_free(ctx_out_ggml);
  346. }
  347. };
  348. static void print_usage(int argc, char ** argv, const gpt_params & params) {
  349. gpt_params_print_usage(argc, argv, params);
  350. printf("\nexample usage:\n");
  351. printf("\n %s -m base-model.gguf --lora lora-file.gguf -o merged-model-f16.gguf\n", argv[0]);
  352. printf("\nNOTE: output model is F16\n");
  353. printf("\n");
  354. }
  355. int main(int argc, char ** argv) {
  356. gpt_params params;
  357. if (!gpt_params_parse(argc, argv, params)) {
  358. print_usage(argc, argv, params);
  359. return 1;
  360. }
  361. g_verbose = (params.verbosity == 1);
  362. try {
  363. lora_merge_ctx ctx(params.model, params.lora_adapters, params.lora_outfile, params.cpuparams.n_threads);
  364. ctx.run_merge();
  365. } catch (const std::exception & err) {
  366. fprintf(stderr, "%s\n", err.what());
  367. exit(EXIT_FAILURE);
  368. }
  369. printf("done, output file is %s\n", params.lora_outfile.c_str());
  370. return 0;
  371. }