1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
//! `frink gguf-split`: llama.cpp's `llama-gguf-split`, same flags,
//! same shard names, same `split.*` keys. The work is in
//! `frink_gguf::split`; this module is argument parsing and the
//! progress lines.
use std::path::PathBuf;
use anyhow::{bail, Context, Result};
use clap::Parser;
use frink_gguf::split::{
plan_merge, plan_split, write_merge, write_split, SplitMode, SplitOptions, SplitPlan,
DEFAULT_MAX_TENSORS,
};
use frink_gguf::GgufFile;
#[derive(Parser, Debug)]
pub struct GgufSplitArgs {
/// Split GGUF_IN into `GGUF_OUT-NNNNN-of-MMMMM.gguf` shards. The
/// default when neither operation is given.
#[arg(long, conflicts_with = "merge")]
pub split: bool,
/// Merge the shard set whose FIRST shard is GGUF_IN into GGUF_OUT.
#[arg(long)]
pub merge: bool,
/// Max tensors per shard (llama.cpp's default: 128).
///
/// `Option`, not a `default_value_t`: `--merge` refuses every split
/// option it was given, and a defaulted field cannot say whether
/// the user typed it.
#[arg(long, conflicts_with = "split_max_size")]
pub split_max_tensors: Option<usize>,
/// Max tensor bytes per shard, as `N(M|G)`: decimal megabytes or
/// gigabytes, the way llama.cpp reads them (`128M` is 128,000,000).
#[arg(long, value_parser = parse_split_size)]
pub split_max_size: Option<u64>,
/// Leave the first shard metadata-only, the layout most published
/// multi-file checkpoints use.
#[arg(long)]
pub no_tensor_first_split: bool,
/// Print the split plan (shard count, tensors and size per shard)
/// and write nothing.
#[arg(long)]
pub dry_run: bool,
/// Source GGUF for `--split`; first shard (`...-00001-of-MMMMM.gguf`)
/// for `--merge`.
pub input: PathBuf,
/// Output prefix for `--split` (`out/model` writes
/// `out/model-00001-of-00003.gguf`, ...); output file for `--merge`.
pub output: PathBuf,
}
/// `split_str_to_n_bytes`, `gguf-split.cpp:72-88`: a positive integer
/// followed by `M` (10^6) or `G` (10^9). Lower case is accepted too.
pub fn parse_split_size(s: &str) -> std::result::Result<u64, String> {
let (digits, unit) = match s.char_indices().last() {
Some((i, c)) => (&s[..i], c.to_ascii_uppercase()),
None => return Err("expected N(M|G), for example 4G".into()),
};
let multiplier: u64 = match unit {
'M' => 1_000_000,
'G' => 1_000_000_000,
other => {
return Err(format!(
"supported units are M (megabytes) or G (gigabytes), got '{other}'"
))
}
};
let n: u64 = digits
.parse()
.map_err(|_| format!("'{digits}' is not a whole number"))?;
if n == 0 {
return Err("size must be a positive value".into());
}
n.checked_mul(multiplier)
.ok_or_else(|| format!("{s} does not fit in 64 bits"))
}
impl GgufSplitArgs {
/// The one place the two size flags become a mode:
/// `--split-max-size` wins when given, otherwise tensor mode, and
/// tensor mode is the default with llama.cpp's 128
/// (`gguf-split.cpp:45`, `:161-164`).
pub fn mode(&self) -> SplitMode {
match self.split_max_size {
Some(bytes) => SplitMode::MaxBytes(bytes),
None => SplitMode::MaxTensors(self.split_max_tensors.unwrap_or(DEFAULT_MAX_TENSORS)),
}
}
/// Every option that only means something to `--split`, named,
/// with whether it was typed. `--merge` refuses the ones it was
/// given from THIS list, and the tests walk it, so a flag cannot be
/// added to one and forgotten by the other.
///
/// The destructure is exhaustive with no `..` on purpose: a new
/// field on `GgufSplitArgs` stops compiling here until someone
/// decides which half of the tool it belongs to. The alternative
/// ships a split-only flag that `--merge` accepts and ignores,
/// which is this repo's dominant bug shape.
fn split_only_flags(&self) -> [(&'static str, bool); 3] {
let GgufSplitArgs {
split: _,
merge: _,
split_max_tensors,
split_max_size,
no_tensor_first_split,
dry_run: _,
input: _,
output: _,
} = self;
[
("--split-max-tensors", split_max_tensors.is_some()),
("--split-max-size", split_max_size.is_some()),
("--no-tensor-first-split", *no_tensor_first_split),
]
}
}
pub fn run(args: GgufSplitArgs) -> Result<()> {
if args.merge {
run_merge(&args)
} else {
run_split(&args)
}
}
/// llama.cpp's `print_info` (`gguf-split.cpp:294-308`), plus the file
/// size, since the tool's reason to exist is fitting a size limit.
fn print_plan(plan: &SplitPlan) {
println!("n_split: {}", plan.shards.len());
for (i, shard) in plan.shards.iter().enumerate() {
println!(
"split {:05}: n_tensors = {}, total_size = {}M (file {} bytes)",
i + 1,
shard.tensors.len(),
(shard.header_bytes as u64 + shard.data_bytes) / 1_000_000,
shard.file_bytes
);
}
}
fn run_split(args: &GgufSplitArgs) -> Result<()> {
let source =
GgufFile::open(&args.input).with_context(|| format!("opening {}", args.input.display()))?;
let opts = SplitOptions {
mode: args.mode(),
no_tensor_first_split: args.no_tensor_first_split,
};
let plan = plan_split(&source, &opts)
.with_context(|| format!("planning a split of {}", args.input.display()))?;
print_plan(&plan);
if args.dry_run {
println!("dry run: nothing written");
return Ok(());
}
let paths = write_split(&source, &plan, &args.output, |path| {
println!("Writing file {} ...", path.display());
})?;
eprintln!(
"gguf_split: {} gguf split written with a total of {} tensors.",
paths.len(),
plan.n_tensors
);
Ok(())
}
fn run_merge(args: &GgufSplitArgs) -> Result<()> {
// llama.cpp parses the split options in merge mode and then never
// reads them, so `--merge --split-max-size 1G` silently does
// nothing there. Refusing names what was ignored instead.
let given: Vec<&str> = args
.split_only_flags()
.iter()
.filter(|(_, typed)| *typed)
.map(|(name, _)| *name)
.collect();
if !given.is_empty() {
bail!(
"--merge takes no split options, but {} was given; a merge writes one file, so \
there is no shard size to choose",
given.join(", ")
);
}
eprintln!(
"gguf_merge: {} -> {}",
args.input.display(),
args.output.display()
);
let plan = plan_merge(&args.input)?;
for path in plan.shard_paths() {
eprintln!("gguf_merge: reading metadata {} ... done", path.display());
}
println!(
"n_split: {}, n_tensors: {}",
plan.shard_paths().len(),
plan.tensors.len()
);
if args.dry_run {
println!("dry run: nothing written");
return Ok(());
}
write_merge(&plan, &args.output)?;
eprintln!(
"gguf_merge: {} merged from {} split with {} tensors.",
args.output.display(),
plan.shard_paths().len(),
plan.tensors.len()
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn parse(argv: &[&str]) -> GgufSplitArgs {
let mut full = vec!["gguf-split"];
full.extend_from_slice(argv);
GgufSplitArgs::try_parse_from(full)
.unwrap_or_else(|e| panic!("`{}` did not parse: {e}", argv.join(" ")))
}
/// llama.cpp's units are decimal (`gguf-split.cpp:77`, `:80`):
/// `4G` is 4,000,000,000, not 2^32. A binary reading would produce
/// shards 7% larger than the limit the user typed.
#[test]
fn split_size_units_are_decimal_like_llama_cpp() {
assert_eq!(parse_split_size("128M").unwrap(), 128_000_000);
assert_eq!(parse_split_size("4G").unwrap(), 4_000_000_000);
assert_eq!(parse_split_size("4g").unwrap(), 4_000_000_000);
for bad in ["4", "4K", "0G", "-1G", "G", "", "4.5G"] {
assert!(parse_split_size(bad).is_err(), "{bad:?} parsed");
}
}
/// Without either flag the mode is tensor mode at llama.cpp's 128
/// (`gguf-split.cpp:45`, `:161-164`); a size flag switches mode.
#[test]
fn the_default_mode_is_128_tensors_and_a_size_flag_switches_it() {
let args = parse(&["in.gguf", "out"]);
assert_eq!(args.mode(), SplitMode::MaxTensors(DEFAULT_MAX_TENSORS));
assert_eq!(DEFAULT_MAX_TENSORS, 128);
assert!(!args.merge && !args.dry_run && !args.no_tensor_first_split);
let args = parse(&["--split-max-size", "2G", "in.gguf", "out"]);
assert_eq!(args.mode(), SplitMode::MaxBytes(2_000_000_000));
let args = parse(&["--split-max-tensors", "7", "in.gguf", "out"]);
assert_eq!(args.mode(), SplitMode::MaxTensors(7));
}
/// `gguf-split.cpp:119` and `:135`: the two operations and the two
/// limits are each mutually exclusive.
#[test]
fn conflicting_flags_are_refused_at_parse_time() {
for argv in [
vec!["--split", "--merge", "in.gguf", "out"],
vec![
"--split-max-tensors",
"3",
"--split-max-size",
"1G",
"in.gguf",
"out",
],
] {
let mut full = vec!["gguf-split"];
full.extend_from_slice(&argv);
assert!(
GgufSplitArgs::try_parse_from(&full).is_err(),
"{argv:?} parsed"
);
}
}
/// Every split-only option has to be REFUSED by `--merge`, not
/// parsed and dropped: llama.cpp accepts `--merge --split-max-size
/// 1G` and ignores it. The list is walked rather than restated, so
/// a new flag that `split_only_flags` classifies is covered here
/// the moment it is added; the exhaustive destructure there is what
/// stops a new flag from being classified as neither.
#[test]
fn every_split_only_flag_is_refused_by_merge_and_named_in_the_refusal() {
let value_of = |flag: &str| match flag {
"--split-max-tensors" => Some("4"),
"--split-max-size" => Some("1G"),
_ => None,
};
let flags = parse(&["in.gguf", "out"]).split_only_flags();
assert_eq!(flags.len(), 3, "a flag was added without a case here");
for (flag, typed) in flags {
assert!(!typed, "`{flag}` reads as typed when it was not");
let mut argv = vec!["--merge", flag];
argv.extend(value_of(flag));
argv.extend(["in.gguf", "out"]);
let args = parse(&argv);
assert!(
args.split_only_flags()
.iter()
.any(|(name, typed)| *name == flag && *typed),
"`{flag}` did not register as typed"
);
let err = run_merge(&args).unwrap_err().to_string();
assert!(
err.contains(flag),
"merge with `{flag}` must name it; got: {err}"
);
}
}
}