export-lora.cpp 15 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. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  46. std::string result;
  47. for (size_t pos = 0; ; pos += search.length()) {
  48. auto new_pos = s.find(search, pos);
  49. if (new_pos == std::string::npos) {
  50. result += s.substr(pos, s.size() - pos);
  51. break;
  52. }
  53. result += s.substr(pos, new_pos - pos) + replace;
  54. pos = new_pos;
  55. }
  56. s = std::move(result);
  57. }
  58. struct file_input {
  59. struct ggml_context * ctx_meta = nullptr;
  60. struct gguf_context * ctx_gguf = nullptr;
  61. std::ifstream f_in;
  62. std::map<std::string, ggml_tensor *> tensors;
  63. float alpha;
  64. float scale;
  65. file_input(std::string & fname, float scale): f_in(fname, std::ios::binary), scale(scale) {
  66. if (!f_in.is_open()) {
  67. throw std::runtime_error("failed to open input gguf from " + fname);
  68. }
  69. ctx_gguf = load_gguf(fname, &ctx_meta);
  70. alpha = get_kv_f32(ctx_gguf, "adapter.lora.alpha");
  71. printf("%s: loaded gguf from %s\n", __func__, fname.c_str());
  72. for (ggml_tensor * cur = ggml_get_first_tensor(ctx_meta); cur; cur = ggml_get_next_tensor(ctx_meta, cur)) {
  73. std::string name(cur->name);
  74. tensors[name] = cur;
  75. if (g_verbose) {
  76. printf("%s: %s\n", __func__, cur->name);
  77. }
  78. }
  79. }
  80. ggml_tensor * get_tensor(std::string name) {
  81. if (tensors.find(name) == tensors.end()) {
  82. return nullptr;
  83. }
  84. return tensors[name];
  85. }
  86. void read_tensor_data(std::string name, std::vector<uint8_t> & buf) {
  87. if (tensors.find(name) == tensors.end()) {
  88. throw std::runtime_error("cannot find tensor with name: " + name);
  89. }
  90. auto len = ggml_nbytes(tensors[name]);
  91. if (buf.size() < len) {
  92. buf.resize(len);
  93. }
  94. auto i_tensor_in = gguf_find_tensor(ctx_gguf, name.c_str()); // idx of tensor in the input file
  95. auto offset = gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, i_tensor_in);
  96. f_in.seekg(offset);
  97. f_in.read((char* )buf.data(), len);
  98. }
  99. ~file_input() {
  100. gguf_free(ctx_gguf);
  101. ggml_free(ctx_meta);
  102. }
  103. };
  104. struct lora_merge_ctx {
  105. // input base model + adapters
  106. file_input base_model;
  107. std::vector<std::unique_ptr<file_input>> adapters;
  108. // for computing merged tensor
  109. int n_threads;
  110. ggml_backend_t backend = nullptr;
  111. ggml_gallocr_t allocr = nullptr;
  112. std::vector<uint8_t> read_buf;
  113. // output file
  114. struct gguf_context * ctx_out;
  115. struct ggml_context * ctx_out_ggml;
  116. std::ofstream fout;
  117. lora_merge_ctx(
  118. std::string & base_fname,
  119. std::vector<std::tuple<std::string, float>> & lora_files,
  120. std::string & outfile,
  121. int n_threads) : base_model(base_fname, 0), n_threads(n_threads), fout(outfile, std::ios::binary) {
  122. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  123. if (gguf_find_key(base_model.ctx_gguf, LLM_KV_SPLIT_COUNT) >= 0) {
  124. throw std::runtime_error("split model is not yet supported");
  125. }
  126. for (auto lora_inp : lora_files) {
  127. auto fname = std::get<0>(lora_inp);
  128. auto scale = std::get<1>(lora_inp);
  129. std::unique_ptr<file_input> adapter(new file_input(fname, scale));
  130. check_metadata_lora(adapter.get());
  131. adapters.push_back(std::move(adapter));
  132. }
  133. ctx_out = gguf_init_empty();
  134. struct ggml_init_params params = {
  135. /*.mem_size =*/ gguf_get_n_tensors(base_model.ctx_gguf)*ggml_tensor_overhead(),
  136. /*.mem_buffer =*/ NULL,
  137. /*.no_alloc =*/ true,
  138. };
  139. ctx_out_ggml = ggml_init(params);
  140. backend = ggml_backend_cpu_init();
  141. allocr = ggml_gallocr_new(ggml_backend_get_default_buffer_type(backend));
  142. }
  143. void check_metadata_lora(file_input * adapter) {
  144. auto general_type = get_kv_str(adapter->ctx_gguf, "general.type");
  145. if (general_type != "adapter") {
  146. throw std::runtime_error("expect general.type to be 'adapter', but got: " + general_type);
  147. }
  148. auto adapter_type = get_kv_str(adapter->ctx_gguf, "adapter.type");
  149. if (adapter_type != "lora") {
  150. throw std::runtime_error("expect adapter.type to be 'lora', but got: " + adapter_type);
  151. }
  152. auto general_arch_base = get_kv_str(base_model.ctx_gguf, "general.architecture");
  153. auto general_arch_lora = get_kv_str(adapter->ctx_gguf, "general.architecture");
  154. if (general_arch_base != general_arch_lora) {
  155. throw std::runtime_error("model arch and LoRA arch mismatch");
  156. }
  157. }
  158. ggml_type get_out_tensor_type(struct ggml_tensor * t) {
  159. if (t->type == GGML_TYPE_F32) {
  160. return GGML_TYPE_F32;
  161. } else {
  162. return GGML_TYPE_F16;
  163. }
  164. }
  165. void run_merge() {
  166. // prepare metadata
  167. gguf_set_kv(ctx_out, base_model.ctx_gguf);
  168. // output is forced to f16 for now
  169. gguf_set_val_u32(ctx_out, "general.file_type", LLAMA_FTYPE_MOSTLY_F16);
  170. // check if all lora adapters have the same tensors
  171. // TODO: remove this when we can support merging subset of adapters. Ref: https://github.com/ggerganov/llama.cpp/pull/8607#discussion_r1686027777
  172. 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.";
  173. if (adapters.size() > 1) {
  174. for (size_t i = 1; i < adapters.size(); ++i) {
  175. if (adapters[0]->tensors.size() != adapters[i]->tensors.size()) {
  176. throw std::runtime_error(err_no_subset_adapter);
  177. }
  178. for (auto & it : adapters[i]->tensors) {
  179. if (adapters[0]->get_tensor(it.first) == nullptr) {
  180. throw std::runtime_error(err_no_subset_adapter);
  181. }
  182. }
  183. }
  184. }
  185. // if true, this tensor can be lora-merged. if false, we skip merging and just copy data to outfile
  186. std::vector<std::pair<struct ggml_tensor *, bool>> base_tensors;
  187. for (auto & it : base_model.tensors) {
  188. bool t_a = true;
  189. bool t_b = true;
  190. for (auto & adapter : adapters) {
  191. t_a &= nullptr != adapter->get_tensor(it.first + ".lora_a");
  192. t_b &= nullptr != adapter->get_tensor(it.first + ".lora_b");
  193. }
  194. auto base_tensor = it.second;
  195. struct ggml_tensor * out_tensor;
  196. if (!t_a && !t_b) {
  197. // only copy
  198. out_tensor = ggml_dup_tensor(ctx_out_ggml, base_tensor);
  199. ggml_set_name(out_tensor, base_tensor->name);
  200. base_tensors.push_back(std::make_pair(out_tensor, false));
  201. } else if (t_a && t_b) {
  202. // need merging
  203. out_tensor = ggml_dup_tensor(ctx_out_ggml, base_tensor);
  204. out_tensor->type = get_out_tensor_type(base_tensor);
  205. ggml_set_name(out_tensor, base_tensor->name);
  206. base_tensors.push_back(std::make_pair(out_tensor, true));
  207. } else {
  208. throw std::runtime_error("tensor " + it.first + " missing either lora_a or lora_b");
  209. }
  210. gguf_add_tensor(ctx_out, out_tensor);
  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 : base_tensors) {
  220. if (it.second) {
  221. merge_tensor(it.first);
  222. n_merged++;
  223. } else {
  224. copy_tensor(it.first);
  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__, base_tensors.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) {
  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()*(1+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 = ggml_dup_tensor(ctx, base);
  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. inp_a[i] = ggml_dup_tensor(ctx, t_a);
  264. inp_b[i] = ggml_dup_tensor(ctx, t_b);
  265. }
  266. ggml_backend_buffer_t buffer = ggml_backend_alloc_ctx_tensors(ctx, backend);
  267. // load data to backend buffer
  268. base_model.read_tensor_data(name_base, read_buf);
  269. ggml_backend_tensor_set(inp, read_buf.data(), 0, ggml_nbytes(inp));
  270. for (size_t i = 0; i < adapters.size(); ++i) {
  271. adapters[i]->read_tensor_data(name_lora_a, read_buf);
  272. ggml_backend_tensor_set(inp_a[i], read_buf.data(), 0, ggml_nbytes(inp_a[i]));
  273. adapters[i]->read_tensor_data(name_lora_b, read_buf);
  274. ggml_backend_tensor_set(inp_b[i], read_buf.data(), 0, ggml_nbytes(inp_b[i]));
  275. }
  276. // build graph
  277. struct ggml_cgraph * gf;
  278. {
  279. static size_t buf_size = ggml_tensor_overhead()*GGML_DEFAULT_GRAPH_SIZE + ggml_graph_overhead();
  280. static std::vector<uint8_t> buf(buf_size);
  281. struct ggml_init_params params0 = {
  282. /*.mem_size =*/ buf_size,
  283. /*.mem_buffer =*/ buf.data(),
  284. /*.no_alloc =*/ true,
  285. };
  286. struct ggml_context * ctx0 = ggml_init(params0);
  287. gf = ggml_new_graph(ctx0);
  288. struct ggml_tensor * cur = inp;
  289. for (size_t i = 0; i < adapters.size(); ++i) {
  290. struct ggml_tensor * a_T = ggml_cont(ctx0, ggml_transpose(ctx0, inp_a[i]));
  291. struct ggml_tensor * delta = ggml_mul_mat(ctx0, a_T, inp_b[i]);
  292. // scale
  293. const float alpha = adapters[i]->alpha;
  294. const float rank = (float) inp_b[i]->ne[0];
  295. const float scale = alpha ? adapters[i]->scale * alpha / rank : adapters[i]->scale;
  296. delta = ggml_scale(ctx0, delta, scale);
  297. cur = ggml_add(ctx0, cur, delta);
  298. printf("%s : + merging from adapter[%ld]\n", __func__, i);
  299. printf("%s : input_scale=%f calculated_scale=%f rank=%d\n", __func__, adapters[i]->scale, scale, (int) inp_b[i]->ne[0]);
  300. }
  301. cur = ggml_cast(ctx0, cur, get_out_tensor_type(base));
  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_adapter, 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. }