gguf-split.cpp 19 KB

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