Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ pub fn build(b: *std.Build) void {
const cost_run = b.addRunArtifact(cost_cases);
b.step("test-cost-rule", "CPU scripted window and interleaved head timing").dependOn(&cost_run.step);
test_step.dependOn(&cost_run.step);
merge_build.targets(b, target, optimize); // tf-merge-check and test-merge, host only on every OS
merge_build.targets(b, target, optimize); // tensorfold merge's tests and tf-merge-check, host only on every OS
switch (target.result.os.tag) {
.macos => metalTargets(b, target, optimize, draft_ids, build_options, test_step),
.linux => cuda_build.targets(b, target, optimize, draft_ids, build_options),
Expand Down Expand Up @@ -216,7 +216,7 @@ fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.b
.target = target,
.optimize = .ReleaseSafe,
.link_libc = true,
.imports = &.{ .{ .name = "engine_api", .module = api }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "template", .module = template }, .{ .name = "native_engines", .module = engines }, .{ .name = "checkpoint_cli", .module = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cli.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "native_engines", .module = engines }, exlr8_build.cliImport(b, target, .ReleaseSafe, engine) } }) } },
.imports = &.{ .{ .name = "engine_api", .module = api }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "template", .module = template }, .{ .name = "native_engines", .module = engines }, .{ .name = "checkpoint_cli", .module = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cli.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "native_engines", .module = engines }, exlr8_build.cliImport(b, target, .ReleaseSafe, engine), .{ .name = "core", .module = engine } } }) } },
}) });
exe.root_module.addOptions("build_options", build_options);
_ = server_build.addTo(b, exe.root_module, target, .ReleaseSafe);
Expand Down Expand Up @@ -483,7 +483,7 @@ fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.b
.target = target,
.optimize = .ReleaseSafe,
.link_libc = true,
.imports = &.{ .{ .name = "native_engines", .module = engines }, exlr8_build.cliImport(b, target, optimize, mods.engine) },
.imports = &.{ .{ .name = "native_engines", .module = engines }, exlr8_build.cliImport(b, target, optimize, mods.engine), .{ .name = "core", .module = mods.engine } },
}) });
const run_cli_tests = b.addRunArtifact(cli_tests);
test_step.dependOn(&run_cli_tests.step);
Expand Down
20 changes: 20 additions & 0 deletions docs/quantization.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,26 @@ When the dense source and the conversion scheme match how a checkpoint was made,
`zig build tf-merge-check` builds a check of that: `tf-merge-check --quantizer DENSE SHIPPED MODULE...` quantizes each named dense tensor and compares it with the shipped one, reporting the share of equal scales, biases, codes and whole groups.
A dense tensor of another shape, size or dtype than the shipped projection, and any non-finite value or stored scale, is refused naming the tensor.

## Merging a LoRA

`tensorfold merge DENSE ADAPTER OUT --quantize SHIPPED` folds a PEFT LoRA into a quantized checkpoint without a Python toolchain or a GPU.
`DENSE` is the checkpoint's bf16 source, `ADAPTER` a PEFT folder and `SHIPPED` the MLX affine 4-bit checkpoint to match; `OUT` must not exist or must be empty.
For each tensor the adapter names, `(alpha / r) * (B * A)` is added to the dense weights and the result is quantized fresh at the shipped tensor's bits and group as above.
The product is accumulated in FP64 in order and scaled once, so a zero sum gives an exactly zero delta; a sum that is not exact in FP64 is not made exact.
Folding the adapter into the already-quantized weights instead keeps only a small part of its effect, which is why the dense base is required.
Every other tensor, shard, index and `config.json` is copied byte for byte from `SHIPPED`; with a zero adapter that is the whole checkpoint.
The merge is staged in a sibling folder and renamed to `OUT` only when everything has succeeded, so a failure before publication leaves no `OUT`; the rename replaces an empty `OUT` atomically and never a non-empty one.
A module is merged when `SHIPPED` holds its `.weight`, `.scales` and `.biases` as rank-2 tensors in the 4-bit affine layout and `DENSE` holds a rank-2 `.weight` of the same shape, so attention, MLP and linear-attention projections all qualify; the checkpoint decides, not a list of names.
A module may be named in either checkpoint's namespace: the exact name is tried first, then one table of prefix rewrites (`model.language_model.` and `language_model.model.`) in both directions; a module that resolves to no pair of names present in both folders, or to more than one, is refused naming each pair tried.
It refuses, naming the tensor and the reason, anything else: modules not quantized in `SHIPPED` (norms, embeddings), stacked or rank-3 expert tensors, fused projections, other bit widths, DoRA and rsLoRA, shard names that leave the folder, subdirectories, dangling symlinks and special files among its inputs, shards whose tensor ranges overlap, non-finite weights, factors or stored scales, duplicate PEFT keys, and shape mismatches.
`tf-merge-check DENSE ADAPTER OUT SHIPPED` holds a merged folder to these gates:
- the exact file set and lengths of `SHIPPED`, and every byte outside the touched tensors, identical;
- every written group equal, byte for byte, to a recomputation from `DENSE` and `ADAPTER`, with the number of groups compared reported;
- aggregate RMS error against an FP64 reference at most twice the shipped quantization's: a sanity net for a gross fault such as a wrong scale or a sign error, not a quality gate, since a delta that widens the groups' ranges legitimately coarsens the grid by a few percent (the ratios, including the worst-column one, are printed);
- for an adapter with no effect (alpha 0, or an all-zero factor, negative zero included), byte identity and ratios of exactly 1.

The recomputation shares the merge's arithmetic, so it checks that what was written is what the code computed; the independent evidence is the pinned vectors and the byte identity of the quantizer with shipped tensors.

## Scope and qualification

In the Python 0.6.6 engine, these additions cover MLX affine safetensors checkpoints for the dense Qwen family. The
Expand Down
2 changes: 1 addition & 1 deletion zig/build/cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ fn engines(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builti

/// The checkpoint subcommands' module: `models`, `info` and `pull` over the CUDA families.
fn checkpointCli(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, strip: ?bool, engines_mod: *std.Build.Module, core: *std.Build.Module) *std.Build.Module {
return b.createModule(.{ .root_source_file = b.path("zig/src/cli/cli.zig"), .target = target, .optimize = optimize, .link_libc = true, .strip = strip, .imports = &.{ .{ .name = "native_engines", .module = engines_mod }, exlr8_build.cliImport(b, target, optimize, core) } });
return b.createModule(.{ .root_source_file = b.path("zig/src/cli/cli.zig"), .target = target, .optimize = optimize, .link_libc = true, .strip = strip, .imports = &.{ .{ .name = "native_engines", .module = engines_mod }, exlr8_build.cliImport(b, target, optimize, core), .{ .name = "core", .module = core } } });
}

/// `zig build native`: tensorfold-native with the CUDA engines into zig-out/native/bin, as the Metal build makes it.
Expand Down
2 changes: 1 addition & 1 deletion zig/build/hip.zig
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ fn server(b: *std.Build, target: std.Build.ResolvedTarget, e: Engine, build_opti
.target = target,
.optimize = .ReleaseSafe,
.link_libc = true,
.imports = &.{ .{ .name = "engine_api", .module = api }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "template", .module = template }, .{ .name = "native_engines", .module = engines }, .{ .name = "checkpoint_cli", .module = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cli.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "native_engines", .module = engines }, exlr8_build.cliImport(b, target, .ReleaseSafe, e.hip.import_table.get("core").?) } }) } },
.imports = &.{ .{ .name = "engine_api", .module = api }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "template", .module = template }, .{ .name = "native_engines", .module = engines }, .{ .name = "checkpoint_cli", .module = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cli.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "native_engines", .module = engines }, exlr8_build.cliImport(b, target, .ReleaseSafe, e.hip.import_table.get("core").?), .{ .name = "core", .module = e.hip.import_table.get("core").? } } }) } },
}) });
exe.root_module.addOptions("build_options", build_options);
_ = @import("server.zig").addTo(b, exe.root_module, target, .ReleaseSafe);
Expand Down
8 changes: 4 additions & 4 deletions zig/build/merge.zig
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
//! The MLX affine 4-bit quantizer's host checks: tf-merge-check and its tests, on every OS.
//! The MLX quantizer's and `tensorfold merge`'s host checks: tf-merge-check and its tests, on every OS.

const std = @import("std");

/// `tf-merge-check --quantizer` and the tests of the MLX quantizer it uses: host only, no model, no GPU.
/// `tf-merge-check` and the tests of the MLX quantizer and the folder merge: host only, no model, no GPU.
pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) void {
const merge_mod = b.createModule(.{
.root_source_file = b.path("zig/src/core/lora_merge_dir.zig"),
Expand All @@ -11,14 +11,14 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu
.link_libc = true,
});
const merge_tests = b.addRunArtifact(b.addTest(.{ .root_module = merge_mod }));
b.step("test-merge", "MLX quantizer and tf-merge-check tests (no model, no GPU)").dependOn(&merge_tests.step);
b.step("test-merge", "tensorfold merge: synthetic-tensor and folder tests (no model, no GPU)").dependOn(&merge_tests.step);
const merge_check = b.addExecutable(.{ .name = "tf-merge-check", .root_module = b.createModule(.{
.root_source_file = b.path("zig/tests/merge_check.zig"),
.target = target,
.optimize = optimize,
.link_libc = true,
.imports = &.{.{ .name = "lora_merge", .module = merge_mod }},
}) });
const about = "Check the MLX quantizer against shipped tensors from their dense source";
const about = "Identity and precision gates of tensorfold merge on a base, an adapter and the merged folder, or the quantizer against shipped tensors";
b.step("tf-merge-check", about).dependOn(&b.addInstallArtifact(merge_check, .{}).step);
}
2 changes: 1 addition & 1 deletion zig/build/xpu.zig
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil
const tokenizer = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true });
const template = b.createModule(.{ .root_source_file = b.path("zig/src/core/template/template.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true });
const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true });
const checkpoint_cli = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cli.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "native_engines", .module = engines }, exlr8_build.cliImport(b, target, .ReleaseSafe, core) } });
const checkpoint_cli = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cli.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "native_engines", .module = engines }, exlr8_build.cliImport(b, target, .ReleaseSafe, core), .{ .name = "core", .module = core } } });
const server = b.addExecutable(.{ .name = "tensorfold-native", .root_module = b.createModule(.{
.root_source_file = b.path("zig/src/server/main.zig"),
.target = target,
Expand Down
12 changes: 11 additions & 1 deletion zig/src/cli/cli.zig
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,22 @@ const models = @import("models.zig");
const info = @import("info.zig");
const pull = @import("pull.zig");
const pull_exlr8 = @import("pull_exlr8.zig");
const lora_merge = @import("core").lora_merge;

const usage =
\\usage: tensorfold models
\\ tensorfold info MODEL
\\ tensorfold pull REPO[@REVISION]
\\ tensorfold pull REPO[@REVISION] --exlr8 PROFILE --node R/N --dir DIR
\\ tensorfold merge DENSE ADAPTER OUT --quantize SHIPPED
\\
;

/// True when argv starts with a checkpoint subcommand.
pub fn wants(args: []const []const u8) bool {
if (args.len == 0) return false;
const cmd = args[0];
return std.mem.eql(u8, cmd, "models") or std.mem.eql(u8, cmd, "info") or std.mem.eql(u8, cmd, "pull");
return std.mem.eql(u8, cmd, "models") or std.mem.eql(u8, cmd, "info") or std.mem.eql(u8, cmd, "pull") or std.mem.eql(u8, cmd, "merge");
}

/// Runs a checkpoint subcommand; `argv` is argv[1..] as in cluster.cli.main.
Expand Down Expand Up @@ -51,6 +53,13 @@ pub fn main(init: std.process.Init, argv: []const [:0]const u8) !u8 {
if (node) |o| return pull_exlr8.run(a, init.io, &out.interface, &err.interface, env, args[1], o);
return pull.run(a, init.io, &out.interface, &err.interface, env, null, args[1]);
}
if (std.mem.eql(u8, args[0], "merge")) {
if (args.len != 6 or !std.mem.eql(u8, args[4], "--quantize")) {
try err.interface.writeAll(usage);
return 2;
}
return lora_merge.run(init.gpa, init.io, &out.interface, &err.interface, args[1], args[2], args[3], args[5]);
}
if (args.len != 2) {
try err.interface.writeAll(usage);
return 2;
Expand All @@ -61,5 +70,6 @@ pub fn main(init: std.process.Init, argv: []const [:0]const u8) !u8 {
test "wants only the checkpoint subcommands" {
try std.testing.expect(wants(&.{"models"}));
try std.testing.expect(wants(&.{ "info", "Org/Flash" }));
try std.testing.expect(wants(&.{ "merge", "dense", "adapter", "out", "--quantize", "shipped" }));
try std.testing.expect(!wants(&.{"run"}) and !wants(&.{}) and !wants(&.{"serve"}));
}
Loading
Loading