export-lora.cpp 16 KB

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