gguf-split.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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 * 1000 * 1000; // megabytes
  58. } else if (str.back() == 'G') {
  59. sscanf(str.c_str(), "%d", &n);
  60. n_bytes = (size_t)n * 1000 * 1000 * 1000; // 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 / 1000 / 1000; // 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. // avoid overwriting existing output file
  344. if (std::ifstream(split_params.output.c_str())) {
  345. fprintf(stderr, "%s: output file %s already exists\n", __func__, split_params.output.c_str());
  346. exit(EXIT_FAILURE);
  347. }
  348. std::ofstream fout(split_params.output.c_str(), std::ios::binary);
  349. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  350. auto * ctx_out = gguf_init_empty();
  351. std::vector<uint8_t> read_data;
  352. std::vector<ggml_context *> ctx_metas;
  353. std::vector<gguf_context *> ctx_ggufs;
  354. char split_path[PATH_MAX] = {0};
  355. strncpy(split_path, split_params.input.c_str(), sizeof(split_path) - 1);
  356. char split_prefix[PATH_MAX] = {0};
  357. // First pass to find KV and tensors metadata
  358. for (int i_split = 0; i_split < n_split; i_split++) {
  359. struct ggml_context * ctx_meta = NULL;
  360. struct gguf_init_params params = {
  361. /*.no_alloc = */ true,
  362. /*.ctx = */ &ctx_meta,
  363. };
  364. if (i_split > 0) {
  365. llama_split_path(split_path, sizeof(split_path), split_prefix, i_split, n_split);
  366. }
  367. fprintf(stderr, "%s: reading metadata %s ...", __func__, split_path);
  368. auto * ctx_gguf = gguf_init_from_file(split_path, params);
  369. if (!ctx_gguf) {
  370. fprintf(stderr, "\n%s: failed to load input GGUF from %s\n", __func__, split_params.input.c_str());
  371. exit(EXIT_FAILURE);
  372. }
  373. ctx_ggufs.push_back(ctx_gguf);
  374. ctx_metas.push_back(ctx_meta);
  375. if (i_split == 0) {
  376. auto key_n_split = gguf_find_key(ctx_gguf, LLM_KV_SPLIT_COUNT);
  377. if (key_n_split < 0) {
  378. fprintf(stderr,
  379. "\n%s: input file does not contain %s metadata\n",
  380. __func__,
  381. LLM_KV_SPLIT_COUNT);
  382. gguf_free(ctx_gguf);
  383. ggml_free(ctx_meta);
  384. gguf_free(ctx_out);
  385. fout.close();
  386. exit(EXIT_FAILURE);
  387. }
  388. n_split = gguf_get_val_u16(ctx_gguf, key_n_split);
  389. if (n_split < 1) {
  390. fprintf(stderr,
  391. "\n%s: input file does not contain a valid split count %d\n",
  392. __func__,
  393. n_split);
  394. gguf_free(ctx_gguf);
  395. ggml_free(ctx_meta);
  396. gguf_free(ctx_out);
  397. fout.close();
  398. exit(EXIT_FAILURE);
  399. }
  400. // Verify the file naming and extract split_prefix
  401. if (!llama_split_prefix(split_prefix, sizeof (split_prefix), split_path, i_split, n_split)) {
  402. fprintf(stderr, "\n%s: unexpected input file name: %s"
  403. " i_split=%d"
  404. " n_split=%d\n", __func__,
  405. split_path, i_split, n_split);
  406. gguf_free(ctx_gguf);
  407. ggml_free(ctx_meta);
  408. gguf_free(ctx_out);
  409. fout.close();
  410. exit(EXIT_FAILURE);
  411. }
  412. // Do not trigger merge if we try to merge again the output
  413. gguf_set_val_u16(ctx_gguf, LLM_KV_SPLIT_COUNT, 0);
  414. // Set metadata from the first split
  415. gguf_set_kv(ctx_out, ctx_gguf);
  416. }
  417. auto n_tensors = gguf_get_n_tensors(ctx_gguf);
  418. for (int i_tensor = 0; i_tensor < n_tensors; i_tensor++) {
  419. const char * t_name = gguf_get_tensor_name(ctx_gguf, i_tensor);
  420. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, t_name);
  421. gguf_add_tensor(ctx_out, t);
  422. }
  423. total_tensors += n_tensors;
  424. fprintf(stderr, "\033[3Ddone\n");
  425. }
  426. // placeholder for the meta data
  427. {
  428. auto meta_size = gguf_get_meta_size(ctx_out);
  429. ::zeros(fout, meta_size);
  430. }
  431. // Write tensors data
  432. for (int i_split = 0; i_split < n_split; i_split++) {
  433. llama_split_path(split_path, sizeof(split_path), split_prefix, i_split, n_split);
  434. std::ifstream f_input(split_path, std::ios::binary);
  435. if (!f_input.is_open()) {
  436. fprintf(stderr, "%s: failed to open input GGUF from %s\n", __func__, split_path);
  437. for (uint32_t i = 0; i < ctx_ggufs.size(); i++) {
  438. gguf_free(ctx_ggufs[i]);
  439. ggml_free(ctx_metas[i]);
  440. }
  441. gguf_free(ctx_out);
  442. fout.close();
  443. exit(EXIT_FAILURE);
  444. }
  445. fprintf(stderr, "%s: writing tensors %s ...", __func__, split_path);
  446. auto * ctx_gguf = ctx_ggufs[i_split];
  447. auto * ctx_meta = ctx_metas[i_split];
  448. auto n_tensors = gguf_get_n_tensors(ctx_gguf);
  449. for (int i_tensor = 0; i_tensor < n_tensors; i_tensor++) {
  450. const char * t_name = gguf_get_tensor_name(ctx_gguf, i_tensor);
  451. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, t_name);
  452. auto n_bytes = ggml_nbytes(t);
  453. if (read_data.size() < n_bytes) {
  454. read_data.resize(n_bytes);
  455. }
  456. auto offset = gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, i_tensor);
  457. f_input.seekg(offset);
  458. f_input.read((char *)read_data.data(), n_bytes);
  459. // write tensor data + padding
  460. fout.write((const char *)read_data.data(), n_bytes);
  461. zeros(fout, GGML_PAD(n_bytes, GGUF_DEFAULT_ALIGNMENT) - n_bytes);
  462. }
  463. gguf_free(ctx_gguf);
  464. ggml_free(ctx_meta);
  465. f_input.close();
  466. fprintf(stderr, "\033[3Ddone\n");
  467. }
  468. {
  469. // go back to beginning of file and write the updated metadata
  470. fout.seekp(0);
  471. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  472. gguf_get_meta_data(ctx_out, data.data());
  473. fout.write((const char *)data.data(), data.size());
  474. fout.close();
  475. gguf_free(ctx_out);
  476. }
  477. fprintf(stderr, "%s: %s merged from %d split with %d tensors.\n",
  478. __func__, split_params.output.c_str(), n_split, total_tensors);
  479. }
  480. int main(int argc, const char ** argv) {
  481. split_params params;
  482. split_params_parse(argc, argv, params);
  483. switch (params.operation) {
  484. case SPLIT_OP_SPLIT: gguf_split(params);
  485. break;
  486. case SPLIT_OP_MERGE: gguf_merge(params);
  487. break;
  488. default: split_print_usage(argv[0]);
  489. exit(EXIT_FAILURE);
  490. }
  491. return 0;
  492. }