gguf-split.cpp 20 KB

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