export-lora.cpp 16 KB

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