export-lora.cpp 16 KB

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