gguf-split.cpp 15 KB

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