gguf-split.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. #include "llama.h"
  2. #include "ggml.h"
  3. #include "common.h"
  4. #include <algorithm>
  5. #include <cmath>
  6. #include <cstdint>
  7. #include <cstdlib>
  8. #include <fstream>
  9. #include <ios>
  10. #include <string>
  11. #include <vector>
  12. #include <stdio.h>
  13. #include <fcntl.h>
  14. #include <string.h>
  15. enum split_operation : uint8_t {
  16. SPLIT_OP_SPLIT,
  17. SPLIT_OP_MERGE,
  18. };
  19. static const char * const LLM_KV_GENERAL_SPLIT_I_SPLIT = "general.split";
  20. static const char * const LLM_KV_GENERAL_SPLIT_N_SPLIT = "general.split_count";
  21. static const int SPLIT_FILENAME_MAX = 256;
  22. static const char * const SPLIT_FILENAME_FORMAT = "%s-%05d-of-%05d.gguf";
  23. struct split_params {
  24. split_operation operation = SPLIT_OP_SPLIT;
  25. int n_split_tensors = 128;
  26. std::string input;
  27. std::string output;
  28. };
  29. static void split_print_usage(const char * executable) {
  30. const split_params default_params;
  31. printf("\n");
  32. printf("usage: %s [options] GGUF_IN GGUF_OUT\n", executable);
  33. printf("\n");
  34. printf("Apply a GGUF operation on IN to OUT.");
  35. printf("\n");
  36. printf("options:\n");
  37. printf(" -h, --help show this help message and exit\n");
  38. printf(" --version show version and build info\n");
  39. printf(" --split split GGUF to multiple GGUF (default)\n");
  40. printf(" --split-max-tensors max tensors in each split: default(%d)\n", default_params.n_split_tensors);
  41. printf(" --merge merge multiple GGUF to a single GGUF\n");
  42. printf("\n");
  43. }
  44. static bool split_params_parse_ex(int argc, const char ** argv, split_params & params) {
  45. std::string arg;
  46. const std::string arg_prefix = "--";
  47. bool invalid_param = false;
  48. int arg_idx = 1;
  49. for (; arg_idx < argc && strncmp(argv[arg_idx], "--", 2) == 0; arg_idx++) {
  50. arg = argv[arg_idx];
  51. if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
  52. std::replace(arg.begin(), arg.end(), '_', '-');
  53. }
  54. bool arg_found = false;
  55. if (arg == "-h" || arg == "--help") {
  56. split_print_usage(argv[0]);
  57. exit(0);
  58. }
  59. if (arg == "--version") {
  60. fprintf(stderr, "version: %d (%s)\n", LLAMA_BUILD_NUMBER, LLAMA_COMMIT);
  61. fprintf(stderr, "built with %s for %s\n", LLAMA_COMPILER, LLAMA_BUILD_TARGET);
  62. exit(0);
  63. }
  64. if (arg == "--merge") {
  65. arg_found = true;
  66. params.operation = SPLIT_OP_MERGE;
  67. }
  68. if (arg == "--split") {
  69. arg_found = true;
  70. params.operation = SPLIT_OP_SPLIT;
  71. }
  72. if (arg == "--split-max-tensors") {
  73. if (++arg_idx >= argc) {
  74. invalid_param = true;
  75. break;
  76. }
  77. arg_found = true;
  78. params.n_split_tensors = atoi(argv[arg_idx]);
  79. }
  80. if (!arg_found) {
  81. throw std::invalid_argument("error: unknown argument: " + arg);
  82. }
  83. }
  84. if (invalid_param) {
  85. throw std::invalid_argument("error: invalid parameter for argument: " + arg);
  86. }
  87. if (argc - arg_idx < 2) {
  88. printf("%s: bad arguments\n", argv[0]);
  89. split_print_usage(argv[0]);
  90. return false;
  91. }
  92. params.input = argv[arg_idx++];
  93. params.output = argv[arg_idx++];
  94. return true;
  95. }
  96. static bool split_params_parse(int argc, const char ** argv, split_params & params) {
  97. bool result = true;
  98. try {
  99. if (!split_params_parse_ex(argc, argv, params)) {
  100. split_print_usage(argv[0]);
  101. exit(1);
  102. }
  103. }
  104. catch (const std::invalid_argument & ex) {
  105. fprintf(stderr, "%s\n", ex.what());
  106. split_print_usage(argv[0]);
  107. exit(1);
  108. }
  109. return result;
  110. }
  111. static void zeros(std::ofstream & file, size_t n) {
  112. char zero = 0;
  113. for (size_t i = 0; i < n; ++i) {
  114. file.write(&zero, 1);
  115. }
  116. }
  117. static std::string split_file_name(const std::string & path, int i_split, int n_split) {
  118. char f_split[SPLIT_FILENAME_MAX] = {0};
  119. snprintf(f_split, sizeof(f_split), SPLIT_FILENAME_FORMAT, path.c_str(), i_split + 1, n_split);
  120. return std::string(f_split);
  121. }
  122. struct split_strategy {
  123. const split_params params;
  124. std::ifstream & f_input;
  125. struct gguf_context * ctx_gguf;
  126. struct ggml_context * ctx_meta = NULL;
  127. const int n_tensors;
  128. const int n_split;
  129. int i_split = 0;
  130. int i_tensor = 0;
  131. std::vector<uint8_t> read_data;
  132. struct gguf_context * ctx_out;
  133. std::ofstream fout;
  134. split_strategy(const split_params & params,
  135. std::ifstream & f_input,
  136. struct gguf_context * ctx_gguf,
  137. struct ggml_context * ctx_meta) :
  138. params(params),
  139. f_input(f_input),
  140. ctx_gguf(ctx_gguf),
  141. ctx_meta(ctx_meta),
  142. n_tensors(gguf_get_n_tensors(ctx_gguf)),
  143. n_split(std::ceil(1. * n_tensors / params.n_split_tensors)) {
  144. }
  145. bool should_split() const {
  146. return i_tensor < n_tensors && i_tensor % params.n_split_tensors == 0;
  147. }
  148. void split_start() {
  149. ctx_out = gguf_init_empty();
  150. // Save all metadata in first split only
  151. if (i_split == 0) {
  152. gguf_set_kv(ctx_out, ctx_gguf);
  153. }
  154. gguf_set_val_u8(ctx_out, LLM_KV_GENERAL_SPLIT_I_SPLIT, i_split);
  155. gguf_set_val_u8(ctx_out, LLM_KV_GENERAL_SPLIT_N_SPLIT, n_split);
  156. // populate the original tensors, so we get an initial metadata
  157. for (int i = i_split * params.n_split_tensors; i < n_tensors && i < (i_split + 1) * params.n_split_tensors; ++i) {
  158. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  159. gguf_add_tensor(ctx_out, meta);
  160. }
  161. auto split_name = split_file_name(params.output, i_split, n_split);
  162. fprintf(stderr, "%s: %s ...", __func__, split_name.c_str());
  163. fout = std::ofstream(split_name, std::ios::binary);
  164. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  165. auto meta_size = gguf_get_meta_size(ctx_out);
  166. // placeholder for the meta data
  167. ::zeros(fout, meta_size);
  168. i_split++;
  169. }
  170. void next_tensor() {
  171. const char * t_name = gguf_get_tensor_name(ctx_gguf, i_tensor);
  172. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, t_name);
  173. auto n_bytes = ggml_nbytes(t);
  174. if (read_data.size() < n_bytes) {
  175. read_data.resize(n_bytes);
  176. }
  177. auto offset = gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, i_tensor);
  178. f_input.seekg(offset);
  179. f_input.read((char *)read_data.data(), n_bytes);
  180. t->data = read_data.data();
  181. // write tensor data + padding
  182. fout.write((const char *)t->data, n_bytes);
  183. zeros(fout, GGML_PAD(n_bytes, GGUF_DEFAULT_ALIGNMENT) - n_bytes);
  184. i_tensor++;
  185. }
  186. void split_end() {
  187. // go back to beginning of file and write the updated metadata
  188. fout.seekp(0);
  189. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  190. gguf_get_meta_data(ctx_out, data.data());
  191. fout.write((const char *)data.data(), data.size());
  192. fout.close();
  193. gguf_free(ctx_out);
  194. fprintf(stderr, "\033[3Ddone\n");
  195. }
  196. };
  197. static void gguf_split(const split_params & split_params) {
  198. struct ggml_context * ctx_meta = NULL;
  199. struct gguf_init_params params = {
  200. /*.no_alloc = */ true,
  201. /*.ctx = */ &ctx_meta,
  202. };
  203. std::ifstream f_input(split_params.input.c_str(), std::ios::binary);
  204. if (!f_input.is_open()) {
  205. fprintf(stderr, "%s: failed to open input GGUF from %s\n", __func__, split_params.input.c_str());
  206. exit(1);
  207. }
  208. auto * ctx_gguf = gguf_init_from_file(split_params.input.c_str(), params);
  209. if (!ctx_gguf) {
  210. fprintf(stderr, "%s: failed to load input GGUF from %s\n", __func__, split_params.input.c_str());
  211. exit(1);
  212. }
  213. split_strategy strategy(split_params, f_input, ctx_gguf, ctx_meta);
  214. fprintf(stderr, "%s: %s -> %s (%d tensors per file)\n",
  215. __func__, split_params.input.c_str(),
  216. split_file_name(split_params.output, strategy.i_split, strategy.n_split).c_str(),
  217. split_params.n_split_tensors);
  218. strategy.split_start();
  219. while (strategy.i_tensor < strategy.n_tensors) {
  220. strategy.next_tensor();
  221. if (strategy.should_split()) {
  222. strategy.split_end();
  223. strategy.split_start();
  224. }
  225. }
  226. strategy.split_end();
  227. gguf_free(ctx_gguf);
  228. f_input.close();
  229. fprintf(stderr, "%s: %d gguf split written with a total of %d tensors.\n",
  230. __func__, strategy.n_split, strategy.n_tensors);
  231. }
  232. static void gguf_merge(const split_params & split_params) {
  233. fprintf(stderr, "%s: %s -> %s\n",
  234. __func__, split_params.input.c_str(),
  235. split_params.output.c_str());
  236. int n_split = 1;
  237. int total_tensors = 0;
  238. auto * ctx_out = gguf_init_empty();
  239. std::ofstream fout(split_params.output.c_str(), std::ios::binary);
  240. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  241. std::vector<uint8_t> read_data;
  242. std::vector<ggml_context *> ctx_metas;
  243. std::vector<gguf_context *> ctx_ggufs;
  244. std::string split_prefix;
  245. // First pass to find KV and tensors metadata
  246. for (int i_split = 0; i_split < n_split; i_split++) {
  247. struct ggml_context * ctx_meta = NULL;
  248. struct gguf_init_params params = {
  249. /*.no_alloc = */ true,
  250. /*.ctx = */ &ctx_meta,
  251. };
  252. auto split_name = split_params.input;
  253. if (i_split > 0) {
  254. split_name = split_file_name(split_prefix, i_split, n_split);
  255. }
  256. fprintf(stderr, "%s: reading metadata %s ...", __func__, split_name.c_str());
  257. auto * ctx_gguf = gguf_init_from_file(split_name.c_str(), params);
  258. if (!ctx_gguf) {
  259. fprintf(stderr, "\n%s: failed to load input GGUF from %s\n", __func__, split_params.input.c_str());
  260. exit(1);
  261. }
  262. ctx_ggufs.push_back(ctx_gguf);
  263. ctx_metas.push_back(ctx_meta);
  264. if (i_split == 0) {
  265. auto key_n_split = gguf_find_key(ctx_gguf, LLM_KV_GENERAL_SPLIT_N_SPLIT);
  266. if (key_n_split < 0) {
  267. fprintf(stderr,
  268. "\n%s: input file does not contain %s metadata\n",
  269. __func__,
  270. LLM_KV_GENERAL_SPLIT_N_SPLIT);
  271. gguf_free(ctx_gguf);
  272. gguf_free(ctx_out);
  273. fout.close();
  274. exit(1);
  275. }
  276. n_split = gguf_get_val_u8(ctx_gguf, key_n_split);
  277. if (n_split < 1) {
  278. fprintf(stderr,
  279. "\n%s: input file does not contain a valid split count %d\n",
  280. __func__,
  281. n_split);
  282. gguf_free(ctx_gguf);
  283. gguf_free(ctx_out);
  284. fout.close();
  285. exit(1);
  286. }
  287. // Do not trigger merge if we try to merge again the output
  288. gguf_set_val_u8(ctx_out, LLM_KV_GENERAL_SPLIT_N_SPLIT, 0);
  289. // Set metadata from the first split
  290. gguf_set_kv(ctx_out, ctx_gguf);
  291. }
  292. // Verify the file naming
  293. {
  294. int i_split_file = 0;
  295. int n_split_file = 0;
  296. const char * i_split_format = "-00000-of-00000.gguf";
  297. if (split_name.size() < strlen(i_split_format)) {
  298. fprintf(stderr, "\n%s: unexpected input file name: %s\n", __func__, split_params.input.c_str());
  299. for (auto * _ctx_gguf : ctx_ggufs) {
  300. gguf_free(_ctx_gguf);
  301. }
  302. gguf_free(ctx_out);
  303. fout.close();
  304. exit(1);
  305. }
  306. split_prefix = split_name.substr(0, split_name.size() - strlen(i_split_format));
  307. const char * split_name_c_str = split_name.c_str();
  308. int n_part = sscanf(&split_name_c_str[0] + split_prefix.size(), "-%d-of-%d", &i_split_file, &n_split_file);
  309. if (n_part != 2 || i_split_file - 1 != i_split || n_split_file != n_split) {
  310. fprintf(stderr, "\n%s: unexpected input file name: %s"
  311. " i_split=%d i_split_file=%d"
  312. " n_split=%d n_split_file=%d\n", __func__,
  313. split_params.input.c_str(),
  314. i_split, i_split_file,
  315. n_split, n_split_file);
  316. for (auto * _ctx_gguf : ctx_ggufs) {
  317. gguf_free(_ctx_gguf);
  318. }
  319. gguf_free(ctx_out);
  320. fout.close();
  321. exit(1);
  322. }
  323. }
  324. auto n_tensors = gguf_get_n_tensors(ctx_gguf);
  325. for (int i_tensor = 0; i_tensor < n_tensors; i_tensor++) {
  326. const char * t_name = gguf_get_tensor_name(ctx_gguf, i_tensor);
  327. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, t_name);
  328. gguf_add_tensor(ctx_out, t);
  329. }
  330. total_tensors += n_tensors;
  331. fprintf(stderr, "\033[3Ddone\n");
  332. }
  333. // placeholder for the meta data
  334. {
  335. auto meta_size = gguf_get_meta_size(ctx_out);
  336. ::zeros(fout, meta_size);
  337. }
  338. // Write tensors data
  339. for (int i_split = 0; i_split < n_split; i_split++) {
  340. auto split_name = split_file_name(split_prefix, i_split, n_split);
  341. std::ifstream f_input(split_name.c_str(), std::ios::binary);
  342. if (!f_input.is_open()) {
  343. fprintf(stderr, "%s: failed to open input GGUF from %s\n", __func__, split_name.c_str());
  344. for (auto * _ctx_gguf : ctx_ggufs) {
  345. gguf_free(_ctx_gguf);
  346. }
  347. gguf_free(ctx_out);
  348. fout.close();
  349. exit(1);
  350. }
  351. fprintf(stderr, "%s: writing tensors %s ...", __func__, split_name.c_str());
  352. auto * ctx_gguf = ctx_ggufs[i_split];
  353. auto * ctx_meta = ctx_metas[i_split];
  354. auto n_tensors = gguf_get_n_tensors(ctx_gguf);
  355. for (int i_tensor = 0; i_tensor < n_tensors; i_tensor++) {
  356. const char * t_name = gguf_get_tensor_name(ctx_gguf, i_tensor);
  357. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, t_name);
  358. auto n_bytes = ggml_nbytes(t);
  359. if (read_data.size() < n_bytes) {
  360. read_data.resize(n_bytes);
  361. }
  362. auto offset = gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, i_tensor);
  363. f_input.seekg(offset);
  364. f_input.read((char *)read_data.data(), n_bytes);
  365. // write tensor data + padding
  366. fout.write((const char *)read_data.data(), n_bytes);
  367. zeros(fout, GGML_PAD(n_bytes, GGUF_DEFAULT_ALIGNMENT) - n_bytes);
  368. }
  369. gguf_free(ctx_gguf);
  370. ggml_free(ctx_meta);
  371. f_input.close();
  372. fprintf(stderr, "\033[3Ddone\n");
  373. }
  374. {
  375. // go back to beginning of file and write the updated metadata
  376. fout.seekp(0);
  377. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  378. gguf_get_meta_data(ctx_out, data.data());
  379. fout.write((const char *)data.data(), data.size());
  380. fout.close();
  381. gguf_free(ctx_out);
  382. }
  383. fprintf(stderr, "%s: %s merged from %d split with %d tensors.\n",
  384. __func__, split_params.output.c_str(), n_split, total_tensors);
  385. }
  386. int main(int argc, const char ** argv) {
  387. if (argc < 3) {
  388. split_print_usage(argv[0]);
  389. }
  390. split_params params;
  391. split_params_parse(argc, argv, params);
  392. switch (params.operation) {
  393. case SPLIT_OP_SPLIT: gguf_split(params);
  394. break;
  395. case SPLIT_OP_MERGE: gguf_merge(params);
  396. break;
  397. default:split_print_usage(argv[0]);
  398. exit(1);
  399. }
  400. return 0;
  401. }