gguf-split.cpp 20 KB

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