gguf-split.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. #include "llama.h"
  2. #include "common.h"
  3. #include <algorithm>
  4. #include <cmath>
  5. #include <cstdlib>
  6. #include <fstream>
  7. #include <string>
  8. #include <vector>
  9. #include <stdio.h>
  10. #include <string.h>
  11. #include <climits>
  12. #include <stdexcept>
  13. #if defined(_WIN32)
  14. #include <windows.h>
  15. #ifndef PATH_MAX
  16. #define PATH_MAX MAX_PATH
  17. #endif
  18. #include <io.h>
  19. #endif
  20. enum split_operation : uint8_t {
  21. SPLIT_OP_SPLIT,
  22. SPLIT_OP_MERGE,
  23. };
  24. struct split_params {
  25. split_operation operation = SPLIT_OP_SPLIT;
  26. size_t n_bytes_split = 0;
  27. int n_split_tensors = 128;
  28. std::string input;
  29. std::string output;
  30. bool no_tensor_first_split = false;
  31. bool dry_run = false;
  32. };
  33. static void split_print_usage(const char * executable) {
  34. const split_params default_params;
  35. printf("\n");
  36. printf("usage: %s [options] GGUF_IN GGUF_OUT\n", executable);
  37. printf("\n");
  38. printf("Apply a GGUF operation on IN to OUT.");
  39. printf("\n");
  40. printf("options:\n");
  41. printf(" -h, --help show this help message and exit\n");
  42. printf(" --version show version and build info\n");
  43. printf(" --split split GGUF to multiple GGUF (enabled by default)\n");
  44. printf(" --merge merge multiple GGUF to a single GGUF\n");
  45. printf(" --split-max-tensors max tensors in each split (default: %d)\n", default_params.n_split_tensors);
  46. printf(" --split-max-size N(M|G) max size per split\n");
  47. printf(" --no-tensor-first-split do not add tensors to the first split (disabled by default)\n");
  48. printf(" --dry-run only print out a split plan and exit, without writing any new files\n");
  49. printf("\n");
  50. }
  51. // return convert string, for example "128M" or "4G" to number of bytes
  52. static size_t split_str_to_n_bytes(std::string str) {
  53. size_t n_bytes = 0;
  54. int n;
  55. if (str.back() == 'M') {
  56. sscanf(str.c_str(), "%d", &n);
  57. n_bytes = (size_t)n * 1024 * 1024; // megabytes
  58. } else if (str.back() == 'G') {
  59. sscanf(str.c_str(), "%d", &n);
  60. n_bytes = (size_t)n * 1024 * 1024 * 1024; // gigabytes
  61. } else {
  62. throw std::invalid_argument("error: supported units are M (megabytes) or G (gigabytes), but got: " + std::string(1, str.back()));
  63. }
  64. if (n <= 0) {
  65. throw std::invalid_argument("error: size must be a positive value");
  66. }
  67. return n_bytes;
  68. }
  69. static void split_params_parse_ex(int argc, const char ** argv, split_params & params) {
  70. std::string arg;
  71. const std::string arg_prefix = "--";
  72. bool invalid_param = false;
  73. int arg_idx = 1;
  74. for (; arg_idx < argc && strncmp(argv[arg_idx], "--", 2) == 0; arg_idx++) {
  75. arg = argv[arg_idx];
  76. if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
  77. std::replace(arg.begin(), arg.end(), '_', '-');
  78. }
  79. bool arg_found = false;
  80. bool is_op_set = false;
  81. bool is_mode_set = false;
  82. if (arg == "-h" || arg == "--help") {
  83. split_print_usage(argv[0]);
  84. exit(0);
  85. }
  86. if (arg == "--version") {
  87. fprintf(stderr, "version: %d (%s)\n", LLAMA_BUILD_NUMBER, LLAMA_COMMIT);
  88. fprintf(stderr, "built with %s for %s\n", LLAMA_COMPILER, LLAMA_BUILD_TARGET);
  89. exit(0);
  90. }
  91. if (arg == "--dry-run") {
  92. arg_found = true;
  93. params.dry_run = true;
  94. }
  95. if (arg == "--no-tensor-first-split") {
  96. arg_found = true;
  97. params.no_tensor_first_split = true;
  98. }
  99. if (is_op_set) {
  100. throw std::invalid_argument("error: either --split or --merge can be specified, but not both");
  101. }
  102. if (arg == "--merge") {
  103. arg_found = true;
  104. is_op_set = true;
  105. params.operation = SPLIT_OP_MERGE;
  106. }
  107. if (arg == "--split") {
  108. arg_found = true;
  109. is_op_set = true;
  110. params.operation = SPLIT_OP_SPLIT;
  111. }
  112. if (is_mode_set) {
  113. throw std::invalid_argument("error: either --split-max-tensors or --split-max-size can be specified, but not both");
  114. }
  115. if (arg == "--split-max-tensors") {
  116. if (++arg_idx >= argc) {
  117. invalid_param = true;
  118. break;
  119. }
  120. arg_found = true;
  121. is_mode_set = true;
  122. params.n_split_tensors = atoi(argv[arg_idx]);
  123. }
  124. if (arg == "--split-max-size") {
  125. if (++arg_idx >= argc) {
  126. invalid_param = true;
  127. break;
  128. }
  129. arg_found = true;
  130. is_mode_set = true;
  131. params.n_bytes_split = split_str_to_n_bytes(argv[arg_idx]);
  132. }
  133. if (!arg_found) {
  134. throw std::invalid_argument("error: unknown argument: " + arg);
  135. }
  136. }
  137. if (invalid_param) {
  138. throw std::invalid_argument("error: invalid parameter for argument: " + arg);
  139. }
  140. if (argc - arg_idx < 2) {
  141. throw std::invalid_argument("error: bad arguments");
  142. }
  143. params.input = argv[arg_idx++];
  144. params.output = argv[arg_idx++];
  145. }
  146. static bool split_params_parse(int argc, const char ** argv, split_params & params) {
  147. bool result = true;
  148. try {
  149. split_params_parse_ex(argc, argv, params);
  150. }
  151. catch (const std::invalid_argument & ex) {
  152. fprintf(stderr, "%s\n", ex.what());
  153. split_print_usage(argv[0]);
  154. exit(EXIT_FAILURE);
  155. }
  156. return result;
  157. }
  158. static void zeros(std::ofstream & file, size_t n) {
  159. char zero = 0;
  160. for (size_t i = 0; i < n; ++i) {
  161. file.write(&zero, 1);
  162. }
  163. }
  164. struct split_strategy {
  165. const split_params params;
  166. std::ifstream & f_input;
  167. struct gguf_context * ctx_gguf;
  168. struct ggml_context * ctx_meta = NULL;
  169. const int n_tensors;
  170. // one ctx_out per one output file
  171. std::vector<struct gguf_context *> ctx_outs;
  172. // temporary buffer for reading in tensor data
  173. std::vector<uint8_t> read_buf;
  174. split_strategy(const split_params & params,
  175. std::ifstream & f_input,
  176. struct gguf_context * ctx_gguf,
  177. struct ggml_context * ctx_meta) :
  178. params(params),
  179. f_input(f_input),
  180. ctx_gguf(ctx_gguf),
  181. ctx_meta(ctx_meta),
  182. n_tensors(gguf_get_n_tensors(ctx_gguf)) {
  183. // because we need to know list of tensors for each file in advance, we will build all the ctx_out for all output splits
  184. int i_split = -1;
  185. struct gguf_context * ctx_out = NULL;
  186. auto new_ctx_out = [&](bool allow_no_tensors) {
  187. i_split++;
  188. if (ctx_out != NULL) {
  189. if (gguf_get_n_tensors(ctx_out) == 0 && !allow_no_tensors) {
  190. fprintf(stderr, "error: one of splits have 0 tensors. Maybe size or tensors limit is too small\n");
  191. exit(EXIT_FAILURE);
  192. }
  193. ctx_outs.push_back(ctx_out);
  194. }
  195. ctx_out = gguf_init_empty();
  196. // Save all metadata in first split only
  197. if (i_split == 0) {
  198. gguf_set_kv(ctx_out, ctx_gguf);
  199. }
  200. gguf_set_val_u16(ctx_out, LLM_KV_SPLIT_NO, i_split);
  201. gguf_set_val_u16(ctx_out, LLM_KV_SPLIT_COUNT, 0); // placeholder
  202. gguf_set_val_i32(ctx_out, LLM_KV_SPLIT_TENSORS_COUNT, n_tensors);
  203. };
  204. // initialize ctx_out for the first split
  205. new_ctx_out(false);
  206. // skip first split if no_tensor_first_split is set
  207. if (params.no_tensor_first_split) {
  208. new_ctx_out(true);
  209. }
  210. // process tensors one by one
  211. size_t curr_tensors_size = 0; // current size by counting only tensors size (without metadata)
  212. for (int i = 0; i < n_tensors; ++i) {
  213. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  214. // calculate the "imaginary" size = the current size + next tensor size
  215. size_t n_bytes = GGML_PAD(ggml_nbytes(t), GGUF_DEFAULT_ALIGNMENT);
  216. size_t next_tensors_size = curr_tensors_size + n_bytes;
  217. if (should_split(i, next_tensors_size)) {
  218. new_ctx_out(false);
  219. curr_tensors_size = n_bytes;
  220. } else {
  221. curr_tensors_size = next_tensors_size;
  222. }
  223. gguf_add_tensor(ctx_out, t);
  224. }
  225. // push the last ctx_out
  226. ctx_outs.push_back(ctx_out);
  227. // set the correct n_split for all ctx_out
  228. for (auto & ctx : ctx_outs) {
  229. gguf_set_val_u16(ctx, LLM_KV_SPLIT_COUNT, ctx_outs.size());
  230. }
  231. }
  232. ~split_strategy() {
  233. for (auto & ctx_out : ctx_outs) {
  234. gguf_free(ctx_out);
  235. }
  236. }
  237. bool should_split(int i_tensor, size_t next_size) {
  238. if (params.n_bytes_split > 0) {
  239. // split by max size per file
  240. return next_size > params.n_bytes_split;
  241. } else {
  242. // split by number of tensors per file
  243. return i_tensor > 0 && i_tensor < n_tensors && i_tensor % params.n_split_tensors == 0;
  244. }
  245. }
  246. void print_info() {
  247. printf("n_split: %ld\n", ctx_outs.size());
  248. int i_split = 0;
  249. for (auto & ctx_out : ctx_outs) {
  250. // re-calculate the real gguf size for each split (= metadata size + total size of all tensors)
  251. size_t total_size = gguf_get_meta_size(ctx_out);
  252. for (int i = 0; i < gguf_get_n_tensors(ctx_out); ++i) {
  253. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_out, i));
  254. total_size += ggml_nbytes(t);
  255. }
  256. total_size = total_size / 1024 / 1024; // convert to megabytes
  257. printf("split %05d: n_tensors = %d, total_size = %ldM\n", i_split + 1, gguf_get_n_tensors(ctx_out), total_size);
  258. i_split++;
  259. }
  260. }
  261. void write() {
  262. int i_split = 0;
  263. int n_split = ctx_outs.size();
  264. for (auto & ctx_out : ctx_outs) {
  265. // construct file path
  266. char split_path[PATH_MAX] = {0};
  267. llama_split_path(split_path, sizeof(split_path), params.output.c_str(), i_split, n_split);
  268. // open the output file
  269. printf("Writing file %s ... ", split_path);
  270. fflush(stdout);
  271. std::ofstream fout = std::ofstream(split_path, std::ios::binary);
  272. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  273. // write metadata
  274. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  275. gguf_get_meta_data(ctx_out, data.data());
  276. fout.write((const char *)data.data(), data.size());
  277. // write tensors
  278. for (int i = 0; i < gguf_get_n_tensors(ctx_out); ++i) {
  279. // read tensor meta and prepare buffer
  280. const char * t_name = gguf_get_tensor_name(ctx_out, i);
  281. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, t_name);
  282. auto n_bytes = ggml_nbytes(t);
  283. read_buf.resize(n_bytes);
  284. // calculate offset
  285. auto i_tensor_in = gguf_find_tensor(ctx_gguf, t_name); // idx of tensor in the input file
  286. auto offset = gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, i_tensor_in);
  287. // copy tensor from input to output file
  288. copy_file_to_file(f_input, fout, offset, n_bytes);
  289. zeros(fout, GGML_PAD(n_bytes, GGUF_DEFAULT_ALIGNMENT) - n_bytes);
  290. }
  291. printf("done\n");
  292. // close the file
  293. fout.close();
  294. i_split++;
  295. }
  296. }
  297. void copy_file_to_file(std::ifstream & f_in, std::ofstream & f_out, const size_t in_offset, const size_t len) {
  298. // TODO: detect OS and use copy_file_range() here for better performance
  299. if (read_buf.size() < len) {
  300. read_buf.resize(len);
  301. }
  302. f_in.seekg(in_offset);
  303. f_in.read((char *)read_buf.data(), len);
  304. f_out.write((const char *)read_buf.data(), len);
  305. }
  306. };
  307. static void gguf_split(const split_params & split_params) {
  308. struct ggml_context * ctx_meta = NULL;
  309. struct gguf_init_params params = {
  310. /*.no_alloc = */ true,
  311. /*.ctx = */ &ctx_meta,
  312. };
  313. std::ifstream f_input(split_params.input.c_str(), std::ios::binary);
  314. if (!f_input.is_open()) {
  315. fprintf(stderr, "%s: failed to open input GGUF from %s\n", __func__, split_params.input.c_str());
  316. exit(EXIT_FAILURE);
  317. }
  318. auto * ctx_gguf = gguf_init_from_file(split_params.input.c_str(), params);
  319. if (!ctx_gguf) {
  320. fprintf(stderr, "%s: failed to load input GGUF from %s\n", __func__, split_params.input.c_str());
  321. exit(EXIT_FAILURE);
  322. }
  323. // prepare the strategy
  324. split_strategy strategy(split_params, f_input, ctx_gguf, ctx_meta);
  325. int n_split = strategy.ctx_outs.size();
  326. strategy.print_info();
  327. if (!split_params.dry_run) {
  328. // write all output splits
  329. strategy.write();
  330. }
  331. // done, clean up
  332. gguf_free(ctx_gguf);
  333. f_input.close();
  334. fprintf(stderr, "%s: %d gguf split written with a total of %d tensors.\n",
  335. __func__, n_split, strategy.n_tensors);
  336. }
  337. static void gguf_merge(const split_params & split_params) {
  338. fprintf(stderr, "%s: %s -> %s\n",
  339. __func__, split_params.input.c_str(),
  340. split_params.output.c_str());
  341. int n_split = 1;
  342. int total_tensors = 0;
  343. auto * ctx_out = gguf_init_empty();
  344. std::ofstream fout(split_params.output.c_str(), std::ios::binary);
  345. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  346. std::vector<uint8_t> read_data;
  347. std::vector<ggml_context *> ctx_metas;
  348. std::vector<gguf_context *> ctx_ggufs;
  349. char split_path[PATH_MAX] = {0};
  350. strncpy(split_path, split_params.input.c_str(), sizeof(split_path) - 1);
  351. char split_prefix[PATH_MAX] = {0};
  352. // First pass to find KV and tensors metadata
  353. for (int i_split = 0; i_split < n_split; i_split++) {
  354. struct ggml_context * ctx_meta = NULL;
  355. struct gguf_init_params params = {
  356. /*.no_alloc = */ true,
  357. /*.ctx = */ &ctx_meta,
  358. };
  359. if (i_split > 0) {
  360. llama_split_path(split_path, sizeof(split_path), split_prefix, i_split, n_split);
  361. }
  362. fprintf(stderr, "%s: reading metadata %s ...", __func__, split_path);
  363. auto * ctx_gguf = gguf_init_from_file(split_path, params);
  364. if (!ctx_gguf) {
  365. fprintf(stderr, "\n%s: failed to load input GGUF from %s\n", __func__, split_params.input.c_str());
  366. exit(EXIT_FAILURE);
  367. }
  368. ctx_ggufs.push_back(ctx_gguf);
  369. ctx_metas.push_back(ctx_meta);
  370. if (i_split == 0) {
  371. auto key_n_split = gguf_find_key(ctx_gguf, LLM_KV_SPLIT_COUNT);
  372. if (key_n_split < 0) {
  373. fprintf(stderr,
  374. "\n%s: input file does not contain %s metadata\n",
  375. __func__,
  376. LLM_KV_SPLIT_COUNT);
  377. gguf_free(ctx_gguf);
  378. ggml_free(ctx_meta);
  379. gguf_free(ctx_out);
  380. fout.close();
  381. exit(EXIT_FAILURE);
  382. }
  383. n_split = gguf_get_val_u16(ctx_gguf, key_n_split);
  384. if (n_split < 1) {
  385. fprintf(stderr,
  386. "\n%s: input file does not contain a valid split count %d\n",
  387. __func__,
  388. n_split);
  389. gguf_free(ctx_gguf);
  390. ggml_free(ctx_meta);
  391. gguf_free(ctx_out);
  392. fout.close();
  393. exit(EXIT_FAILURE);
  394. }
  395. // Verify the file naming and extract split_prefix
  396. if (!llama_split_prefix(split_prefix, sizeof (split_prefix), split_path, i_split, n_split)) {
  397. fprintf(stderr, "\n%s: unexpected input file name: %s"
  398. " i_split=%d"
  399. " n_split=%d\n", __func__,
  400. split_path, i_split, n_split);
  401. gguf_free(ctx_gguf);
  402. ggml_free(ctx_meta);
  403. gguf_free(ctx_out);
  404. fout.close();
  405. exit(EXIT_FAILURE);
  406. }
  407. // Do not trigger merge if we try to merge again the output
  408. gguf_set_val_u16(ctx_gguf, LLM_KV_SPLIT_COUNT, 0);
  409. // Set metadata from the first split
  410. gguf_set_kv(ctx_out, ctx_gguf);
  411. }
  412. auto n_tensors = gguf_get_n_tensors(ctx_gguf);
  413. for (int i_tensor = 0; i_tensor < n_tensors; i_tensor++) {
  414. const char * t_name = gguf_get_tensor_name(ctx_gguf, i_tensor);
  415. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, t_name);
  416. gguf_add_tensor(ctx_out, t);
  417. }
  418. total_tensors += n_tensors;
  419. fprintf(stderr, "\033[3Ddone\n");
  420. }
  421. // placeholder for the meta data
  422. {
  423. auto meta_size = gguf_get_meta_size(ctx_out);
  424. ::zeros(fout, meta_size);
  425. }
  426. // Write tensors data
  427. for (int i_split = 0; i_split < n_split; i_split++) {
  428. llama_split_path(split_path, sizeof(split_path), split_prefix, i_split, n_split);
  429. std::ifstream f_input(split_path, std::ios::binary);
  430. if (!f_input.is_open()) {
  431. fprintf(stderr, "%s: failed to open input GGUF from %s\n", __func__, split_path);
  432. for (uint32_t i = 0; i < ctx_ggufs.size(); i++) {
  433. gguf_free(ctx_ggufs[i]);
  434. ggml_free(ctx_metas[i]);
  435. }
  436. gguf_free(ctx_out);
  437. fout.close();
  438. exit(EXIT_FAILURE);
  439. }
  440. fprintf(stderr, "%s: writing tensors %s ...", __func__, split_path);
  441. auto * ctx_gguf = ctx_ggufs[i_split];
  442. auto * ctx_meta = ctx_metas[i_split];
  443. auto n_tensors = gguf_get_n_tensors(ctx_gguf);
  444. for (int i_tensor = 0; i_tensor < n_tensors; i_tensor++) {
  445. const char * t_name = gguf_get_tensor_name(ctx_gguf, i_tensor);
  446. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, t_name);
  447. auto n_bytes = ggml_nbytes(t);
  448. if (read_data.size() < n_bytes) {
  449. read_data.resize(n_bytes);
  450. }
  451. auto offset = gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, i_tensor);
  452. f_input.seekg(offset);
  453. f_input.read((char *)read_data.data(), n_bytes);
  454. // write tensor data + padding
  455. fout.write((const char *)read_data.data(), n_bytes);
  456. zeros(fout, GGML_PAD(n_bytes, GGUF_DEFAULT_ALIGNMENT) - n_bytes);
  457. }
  458. gguf_free(ctx_gguf);
  459. ggml_free(ctx_meta);
  460. f_input.close();
  461. fprintf(stderr, "\033[3Ddone\n");
  462. }
  463. {
  464. // go back to beginning of file and write the updated metadata
  465. fout.seekp(0);
  466. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  467. gguf_get_meta_data(ctx_out, data.data());
  468. fout.write((const char *)data.data(), data.size());
  469. fout.close();
  470. gguf_free(ctx_out);
  471. }
  472. fprintf(stderr, "%s: %s merged from %d split with %d tensors.\n",
  473. __func__, split_params.output.c_str(), n_split, total_tensors);
  474. }
  475. int main(int argc, const char ** argv) {
  476. split_params params;
  477. split_params_parse(argc, argv, params);
  478. switch (params.operation) {
  479. case SPLIT_OP_SPLIT: gguf_split(params);
  480. break;
  481. case SPLIT_OP_MERGE: gguf_merge(params);
  482. break;
  483. default: split_print_usage(argv[0]);
  484. exit(EXIT_FAILURE);
  485. }
  486. return 0;
  487. }