wdelta 0.3.1__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
wdelta/__init__.py ADDED
@@ -0,0 +1,212 @@
1
+ """
2
+ wdelta — lossless delta compression for fine-tuned models.
3
+
4
+ A packed model is a folder holding one ``.wdz`` file per safetensors shard, every other
5
+ file of the model copied as-is (config, tokenizer, ``.bin`` files, ...) and a
6
+ ``wdelta.json`` manifest naming the base model (Hugging Face repo id + exact commit) and
7
+ the SHA-256 of every file. Unpacking downloads that base if needed and restores every
8
+ file byte-for-byte. Hidden files and folders (names starting with ".") are not packed.
9
+
10
+ import wdelta
11
+ wdelta.pack("my-org/my-finetune", base="meta-llama/Llama-3.1-8B-Instruct", out="packed/")
12
+ path = wdelta.from_pretrained("packed/") # unpacks into a cache, returns the folder
13
+ model = AutoModelForCausalLM.from_pretrained(path)
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import hashlib
18
+ import json
19
+ import os
20
+ import shutil
21
+ import subprocess
22
+ import tempfile
23
+ from pathlib import Path
24
+
25
+ from . import hub
26
+
27
+ __version__ = "0.3.1"
28
+ FORMAT = "wdelta-packed-v1"
29
+ MANIFEST = "wdelta.json"
30
+ CACHE = Path(os.environ.get("WDELTA_CACHE", Path.home() / ".cache" / "wdelta"))
31
+ WEIGHT_EXT = ".safetensors"
32
+
33
+
34
+ # ------------------------------------------------------------------ binary
35
+
36
+ def _binary() -> str:
37
+ """Locate the wdelta executable: $WDELTA_BIN, the copy bundled in the package, or PATH."""
38
+ exe = "wdelta.exe" if os.name == "nt" else "wdelta"
39
+ cands = [os.environ.get("WDELTA_BIN"), str(Path(__file__).parent / "bin" / exe), shutil.which("wdelta")]
40
+ for c in cands:
41
+ if c and Path(c).is_file() and os.access(c, os.X_OK):
42
+ return c
43
+ raise FileNotFoundError("wdelta executable not found; build it with `cargo build --release` and set WDELTA_BIN")
44
+
45
+
46
+ def _run(*args: str, env: dict | None = None) -> str:
47
+ p = subprocess.run([_binary(), *args], capture_output=True, text=True, env=env)
48
+ if p.returncode != 0:
49
+ raise RuntimeError((p.stderr or p.stdout).strip())
50
+ return p.stdout
51
+
52
+
53
+ # ------------------------------------------------------------------ helpers
54
+
55
+ def _resolve(spec: str, kind: str, patterns=None, revision: str | None = None) -> tuple[Path, str | None, str | None]:
56
+ """Return (local_dir, repo_id, commit) for a local folder or a Hugging Face repo id."""
57
+ p = Path(spec)
58
+ if p.is_dir():
59
+ return p, None, None
60
+ repo = spec[3:] if spec.startswith("hf:") else spec
61
+ commit = revision or hub.commit_of(repo)
62
+ local = hub.download(repo, CACHE / kind / repo.replace("/", "__") / commit, patterns=patterns, revision=commit)
63
+ return local, repo, commit
64
+
65
+
66
+ def _model_files(src: Path) -> list[Path]:
67
+ """Every file of a model folder, as paths relative to it. Hidden files and folders (names
68
+ starting with ".", such as download caches and .gitattributes) are left out."""
69
+ return sorted(f.relative_to(src) for f in src.rglob("*")
70
+ if f.is_file() and not any(part.startswith(".") for part in f.relative_to(src).parts))
71
+
72
+
73
+ def _base_dir_for(b_dir: Path, rel: Path) -> str:
74
+ """The base folder (relative to b_dir) whose tensors a shard at `rel` is coded against:
75
+ the matching subfolder of the base if it holds safetensors files, else the base's top level."""
76
+ sub = rel.parent
77
+ if sub != Path(".") and any((b_dir / sub).glob("*" + WEIGHT_EXT)):
78
+ return sub.as_posix()
79
+ return ""
80
+
81
+
82
+ def _sha256(path: Path) -> str:
83
+ h = hashlib.sha256()
84
+ with open(path, "rb") as f:
85
+ for chunk in iter(lambda: f.read(1 << 24), b""):
86
+ h.update(chunk)
87
+ return h.hexdigest()
88
+
89
+
90
+ # ------------------------------------------------------------------ API
91
+
92
+ def pack(finetune: str, base: str, out: str, base_id: str | None = None, base_revision: str | None = None) -> dict:
93
+ """Compress a fine-tuned model against its base.
94
+
95
+ finetune, base: a local folder or a Hugging Face repo id ("org/name").
96
+ base_id: label recorded for the base when `base` is a local folder (normally its repo id),
97
+ so that `unpack` can download it later.
98
+ Returns the manifest.
99
+ """
100
+ ft_dir, ft_repo, ft_commit = _resolve(finetune, "src")
101
+ b_dir, b_repo, b_commit = _resolve(base, "bases", patterns=["*.safetensors", "*.json"], revision=base_revision)
102
+ label = base_id or b_repo or str(b_dir)
103
+ out_dir = Path(out)
104
+ out_dir.mkdir(parents=True, exist_ok=True)
105
+ env = dict(os.environ, WDELTA_BASE_ID=label)
106
+ files = _model_files(ft_dir)
107
+ shards, total_in, total_out = [], 0, 0
108
+ for rel in files:
109
+ if rel.suffix != WEIGHT_EXT or rel.name == MANIFEST:
110
+ continue
111
+ f = ft_dir / rel
112
+ wdz = out_dir / rel.with_name(rel.name + ".wdz")
113
+ wdz.parent.mkdir(parents=True, exist_ok=True)
114
+ bsub = _base_dir_for(b_dir, rel)
115
+ _run("encode", str(b_dir / bsub), str(f), str(wdz), env=env)
116
+ shards.append({"file": rel.as_posix(), "wdz": wdz.relative_to(out_dir).as_posix(), "base_dir": bsub,
117
+ "bytes": f.stat().st_size, "wdz_bytes": wdz.stat().st_size, "sha256": _sha256(f)})
118
+ total_in += f.stat().st_size
119
+ total_out += wdz.stat().st_size
120
+ if not shards:
121
+ raise ValueError(f"no {WEIGHT_EXT} files in {ft_dir}")
122
+ # every other file is copied as-is, with its hash, so unpack restores the complete folder
123
+ coded = {s["file"] for s in shards}
124
+ outputs = {s["wdz"] for s in shards}
125
+ extras = []
126
+ for rel in files:
127
+ if rel.as_posix() in coded or rel.name == MANIFEST:
128
+ continue
129
+ if rel.as_posix() in outputs:
130
+ raise ValueError(f"{rel}: name clashes with a compressed shard; rename it before packing")
131
+ (out_dir / rel).parent.mkdir(parents=True, exist_ok=True)
132
+ shutil.copy2(ft_dir / rel, out_dir / rel)
133
+ extras.append({"file": rel.as_posix(), "bytes": (ft_dir / rel).stat().st_size, "sha256": _sha256(ft_dir / rel)})
134
+ manifest = {
135
+ "format": FORMAT, "wdelta_version": __version__,
136
+ "base": {"repo": label, "revision": b_commit or base_revision},
137
+ "source": {"repo": ft_repo, "revision": ft_commit},
138
+ "shards": shards, "extra_files": [e["file"] for e in extras], "extras": extras,
139
+ "bytes": total_in, "packed_bytes": total_out, "extra_bytes": sum(e["bytes"] for e in extras),
140
+ }
141
+ (out_dir / MANIFEST).write_text(json.dumps(manifest, indent=2))
142
+ return manifest
143
+
144
+
145
+ def info(packed: str) -> dict:
146
+ """Read a packed model's manifest (local folder or Hugging Face repo id)."""
147
+ d = Path(packed)
148
+ if not d.is_dir():
149
+ d = hub.download(packed[3:] if packed.startswith("hf:") else packed,
150
+ CACHE / "packed-meta" / packed.replace("/", "__"), patterns=[MANIFEST])
151
+ return json.loads((d / MANIFEST).read_text())
152
+
153
+
154
+ def unpack(packed: str, out: str, base: str | None = None) -> Path:
155
+ """Restore a packed model into `out`, byte-identical to the original.
156
+
157
+ packed: a local folder or a Hugging Face repo id holding a packed model.
158
+ base: optional local folder with the base model; if omitted, the base recorded in the
159
+ manifest is downloaded (at the recorded commit) into the wdelta cache.
160
+ """
161
+ p_dir, _, _ = _resolve(packed, "packed") if not Path(packed).is_dir() else (Path(packed), None, None)
162
+ m = json.loads((p_dir / MANIFEST).read_text())
163
+ if m.get("format") != FORMAT:
164
+ raise ValueError(f"{p_dir}: not a {FORMAT} folder")
165
+ if base:
166
+ b_dir = Path(base)
167
+ else:
168
+ repo, rev = m["base"]["repo"], m["base"]["revision"]
169
+ if Path(repo).is_dir():
170
+ b_dir = Path(repo)
171
+ else:
172
+ b_dir = hub.download(repo, CACHE / "bases" / repo.replace("/", "__") / (rev or "main"),
173
+ patterns=["*.safetensors", "*.json"], revision=rev)
174
+ out_dir = Path(out).resolve()
175
+ out_dir.parent.mkdir(parents=True, exist_ok=True)
176
+ tmp = Path(tempfile.mkdtemp(prefix=".wdelta-", dir=out_dir.parent)) # same filesystem, so the final rename is atomic
177
+ try:
178
+ for s in m["shards"]:
179
+ dst = tmp / s["file"]
180
+ dst.parent.mkdir(parents=True, exist_ok=True)
181
+ _run("decode", str(b_dir / s.get("base_dir", "")), str(p_dir / s["wdz"]), str(dst)) # checks SHA-256 internally
182
+ for e in m.get("extras") or [{"file": f} for f in m.get("extra_files", [])]:
183
+ src, dst = p_dir / e["file"], tmp / e["file"]
184
+ if not src.is_file():
185
+ raise FileNotFoundError(f"{src}: listed in {MANIFEST} but missing from the packed model")
186
+ dst.parent.mkdir(parents=True, exist_ok=True)
187
+ shutil.copy2(src, dst)
188
+ if "sha256" in e and _sha256(dst) != e["sha256"]:
189
+ raise ValueError(f"{e['file']}: SHA-256 does not match the one recorded at pack time")
190
+ out_dir.parent.mkdir(parents=True, exist_ok=True)
191
+ if out_dir.exists():
192
+ shutil.rmtree(out_dir)
193
+ os.replace(tmp, out_dir)
194
+ finally:
195
+ if tmp.exists():
196
+ shutil.rmtree(tmp, ignore_errors=True)
197
+ return out_dir
198
+
199
+
200
+ def from_pretrained(packed: str, base: str | None = None, cache_dir: str | None = None) -> str:
201
+ """Return a local folder with the unpacked model, ready for `transformers`' from_pretrained.
202
+
203
+ The unpacked copy is cached (keyed by the manifest), so later calls return immediately.
204
+ """
205
+ m = info(packed)
206
+ key = hashlib.sha256(json.dumps(m["shards"], sort_keys=True).encode()).hexdigest()[:16]
207
+ target = Path(cache_dir or CACHE / "unpacked") / key
208
+ done = target / ".wdelta-complete"
209
+ if not done.exists():
210
+ unpack(packed, str(target), base=base)
211
+ done.write_text(m["base"]["repo"] or "")
212
+ return str(target)
wdelta/__main__.py ADDED
@@ -0,0 +1,42 @@
1
+ """Command line: python -m wdelta pack|unpack|info ..."""
2
+ import argparse
3
+ import json
4
+ import sys
5
+
6
+ from . import info, pack, unpack
7
+
8
+
9
+ def main(argv=None):
10
+ ap = argparse.ArgumentParser(prog="wdelta", description="Lossless delta compression for fine-tuned models.")
11
+ sub = ap.add_subparsers(dest="cmd", required=True)
12
+ p = sub.add_parser("pack", help="compress a fine-tune against its base")
13
+ p.add_argument("finetune", help="local folder or Hugging Face repo id")
14
+ p.add_argument("--base", required=True, help="local folder or Hugging Face repo id of the base model")
15
+ p.add_argument("--base-id", help="repo id to record when --base is a local folder")
16
+ p.add_argument("-o", "--out", required=True, help="output folder")
17
+ u = sub.add_parser("unpack", help="restore a packed model (downloads the base if needed)")
18
+ u.add_argument("packed", help="local folder or Hugging Face repo id")
19
+ u.add_argument("-o", "--out", required=True, help="output folder")
20
+ u.add_argument("--base", help="local base model folder (otherwise downloaded)")
21
+ i = sub.add_parser("info", help="show a packed model's manifest")
22
+ i.add_argument("packed")
23
+ a = ap.parse_args(argv)
24
+ if a.cmd == "pack":
25
+ m = pack(a.finetune, a.base, a.out, base_id=a.base_id)
26
+ print(f"packed {len(m['shards'])} shards: {m['bytes'] / 1e9:.2f} GB -> {m['packed_bytes'] / 1e9:.2f} GB "
27
+ f"({100 * m['packed_bytes'] / m['bytes']:.1f}%), base {m['base']['repo']}@{(m['base']['revision'] or '')[:10]}")
28
+ extras = m.get("extras", [])
29
+ if extras:
30
+ print(f"copied {len(extras)} other files uncompressed: {m['extra_bytes'] / 1e9:.2f} GB")
31
+ for e in sorted(extras, key=lambda e: -e["bytes"])[:5]:
32
+ if e["bytes"] >= 100 << 20:
33
+ print(f" {e['file']}: {e['bytes'] / 1e9:.2f} GB (not compressed; only safetensors weights are)")
34
+ elif a.cmd == "unpack":
35
+ print(f"unpacked to {unpack(a.packed, a.out, base=a.base)}")
36
+ else:
37
+ json.dump(info(a.packed), sys.stdout, indent=2)
38
+ print()
39
+
40
+
41
+ if __name__ == "__main__":
42
+ main()
wdelta/bin/wdelta.exe ADDED
Binary file
wdelta/hub.py ADDED
@@ -0,0 +1,58 @@
1
+ """Minimal Hugging Face Hub access: uses huggingface_hub when installed, plain HTTPS otherwise."""
2
+ from __future__ import annotations
3
+
4
+ import fnmatch
5
+ import json
6
+ import os
7
+ import shutil
8
+ import urllib.request
9
+ from pathlib import Path
10
+
11
+ HF = os.environ.get("HF_ENDPOINT", "https://huggingface.co")
12
+
13
+
14
+ def _req(url: str) -> urllib.request.Request:
15
+ r = urllib.request.Request(url)
16
+ tok = os.environ.get("HF_TOKEN")
17
+ if tok:
18
+ r.add_header("Authorization", f"Bearer {tok}")
19
+ return r
20
+
21
+
22
+ def _api(repo: str, revision: str | None = None) -> dict:
23
+ url = f"{HF}/api/models/{repo}" + (f"/revision/{revision}" if revision else "")
24
+ with urllib.request.urlopen(_req(url), timeout=120) as r:
25
+ return json.loads(r.read())
26
+
27
+
28
+ def commit_of(repo: str) -> str:
29
+ """Current commit hash of a repo's main branch."""
30
+ return _api(repo)["sha"]
31
+
32
+
33
+ def download(repo: str, dest: Path, patterns: list[str] | None = None, revision: str | None = None) -> Path:
34
+ """Download the files of `repo` (optionally filtered by glob patterns) into `dest`."""
35
+ dest = Path(dest)
36
+ marker = dest / ".wdelta-download-complete"
37
+ if marker.exists():
38
+ return dest
39
+ dest.mkdir(parents=True, exist_ok=True)
40
+ try:
41
+ from huggingface_hub import snapshot_download
42
+ snapshot_download(repo, revision=revision, local_dir=dest, allow_patterns=patterns,
43
+ token=os.environ.get("HF_TOKEN"))
44
+ except ImportError:
45
+ files = [s["rfilename"] for s in _api(repo, revision).get("siblings", [])]
46
+ if patterns:
47
+ files = [f for f in files if any(fnmatch.fnmatch(f, p) for p in patterns)]
48
+ for f in files:
49
+ out = dest / f
50
+ if out.exists():
51
+ continue
52
+ out.parent.mkdir(parents=True, exist_ok=True)
53
+ url = f"{HF}/{repo}/resolve/{revision or 'main'}/{f}"
54
+ with urllib.request.urlopen(_req(url), timeout=300) as r, open(f"{out}.part", "wb") as w:
55
+ shutil.copyfileobj(r, w, length=1 << 22)
56
+ os.replace(f"{out}.part", out)
57
+ marker.write_text(revision or "main")
58
+ return dest
@@ -0,0 +1,284 @@
1
+ Metadata-Version: 2.4
2
+ Name: wdelta
3
+ Version: 0.3.1
4
+ Summary: Lossless delta compression for fine-tuned models (safetensors)
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Provides-Extra: hub
10
+ Requires-Dist: huggingface_hub>=0.20; extra == "hub"
11
+ Dynamic: license-file
12
+
13
+ # wdelta
14
+
15
+ [![tests](https://github.com/endriasf/wdelta/actions/workflows/tests.yml/badge.svg)](https://github.com/endriasf/wdelta/actions/workflows/tests.yml)
16
+
17
+ Lossless compression for fine-tuned models. A fine-tune is stored as a delta against its
18
+ base model, so it downloads and stores at a fraction of its size, and is restored
19
+ byte-for-byte.
20
+
21
+ > **Status: experimental (v0.3).** The file format may still change before 1.0. Keep your
22
+ > original files until you have verified a restore, and don't use it as your only copy of
23
+ > anything you need to keep long term.
24
+
25
+ ## What it can and cannot do
26
+
27
+ **It can:**
28
+
29
+ - Shrink a fine-tuned model to 5–54% of its size (bf16 safetensors, tested on 10 fine-tunes
30
+ from 4 base models), when the base model it was fine-tuned from is available.
31
+ - Restore the fine-tune bit-for-bit. Nothing is approximated: every restored shard is checked
32
+ against the SHA-256 of the original.
33
+ - Compress bf16 weights without a base model, to about 66.5%. That matches single-model tools
34
+ such as ZipNN and DFloat11; it does not beat them.
35
+ - Pin the exact base: the packed model records the base's Hub repo and commit, plus a hash of
36
+ every base tensor it uses, so a wrong or modified base is rejected instead of producing a
37
+ different model.
38
+ - Pack and restore whole Hugging Face models (weights, config, tokenizer), download the base
39
+ automatically, and hand the restored folder to `transformers`.
40
+
41
+ **It cannot:**
42
+
43
+ - **Help much without the right base.** Savings come from the base model. A model trained from
44
+ scratch, or compared against the wrong base, gets the ~66.5% base-less result at best.
45
+ - **Promise a fixed ratio.** The result depends on how far the fine-tune moved from its base:
46
+ 5.3% for a light security fine-tune (MetaSecAlign), 53% for
47
+ Mistral-7B-Instruct-v0.1. The more the training changed the weights, the less there is to gain.
48
+ - **Make downloads smaller if you don't already have the base.** Restoring needs the base; if
49
+ it isn't on your machine it is downloaded too. The saving is largest when many fine-tunes
50
+ share one base you already have.
51
+ - **Compress anything other than bf16.** fp16, fp32, int8 and other quantized tensors are stored
52
+ uncompressed. GGUF and other non-safetensors formats are not supported.
53
+ - **Reduce memory or speed up inference.** It is a storage and transfer format, like zip.
54
+ Models are fully restored before loading. It is not quantization.
55
+ - **Restore a model whose base has disappeared.** If the base is deleted from the Hub and you
56
+ have no copy, the fine-tune can't be restored.
57
+ - **Prove where a file came from.** The hashes detect corruption and a wrong base. They are not
58
+ signatures: anyone can build a valid `.wdz` of a different model. Trust a packed model only as
59
+ much as you trust its source.
60
+ - **Vouch for untested model types.** Testing covered dense transformer LLMs (Qwen3, Mistral,
61
+ Llama 3.1, 7B–70B). Mixture-of-experts, vision, speech and diffusion models are untested.
62
+ - **Match zstd's speed.** Decoding runs at about 220–240 MB/s on 2 CPU cores, well below
63
+ general-purpose decompressors such as zstd, which typically decode at over 1 GB/s.
64
+
65
+ Whole-model packing (`wdelta-model pack`) compresses every `*.safetensors` file in the model
66
+ folder and its subfolders, and copies every other file (`.bin`, `.pt`, `.onnx`, config,
67
+ tokenizer, ...) **without compression**, so a repo that also ships `pytorch_model.bin` copies of
68
+ its weights will pack to a much larger size. The command lists any large uncompressed files.
69
+ Hidden files and folders (names starting with `.`, such as `.gitattributes`) are not packed.
70
+
71
+ ## How well it works
72
+
73
+ Measured on real fine-tunes, compressed against the base model named on each model card.
74
+ Sizes are % of the original bf16 file; every wdelta output was restored and checked
75
+ byte-for-byte (SHA-256).
76
+
77
+ | Fine-tune | Base | BitX | FM-Delta | wdelta |
78
+ | --- | --- | --- | --- | --- |
79
+ | Llama-3.1-Nemotron-70B-Instruct | Llama-3.1-70B-Instruct | 17.66% | not run | **7.38%** (141 GB → 10.4 GB) |
80
+ | Llama-3.1-8B-Instruct-MetaSecAlign | Llama-3.1-8B-Instruct | 12.68% | 7.66% | **5.34%** |
81
+ | Llama-3.1-SuperNova-Lite | Llama-3.1-8B-Instruct | 22.33% | 16.26% | **13.96%** |
82
+ | KernelLLM | Llama-3.1-8B-Instruct | 47.60% | 39.11% | **35.40%** |
83
+ | Huihui-Qwen3-8B-abliterated-v2 | Qwen3-8B | 10.62% | not run | **7.87%** |
84
+ | WebExplorer-8B | Qwen3-8B | 40.71% | not run | **29.06%** |
85
+ | Goedel-Prover-V2-8B | Qwen3-8B | 50.99% | not run | **40.23%** |
86
+ | OpenHermes-2.5-Mistral-7B | Mistral-7B-v0.1 | 46.18% | not run | **34.05%** |
87
+ | zephyr-7b-beta | Mistral-7B-v0.1 | 49.82% | not run | **37.75%** |
88
+ | Mistral-7B-Instruct-v0.1 | Mistral-7B-v0.1 | 62.37% | not run | **53.44%** |
89
+
90
+ - **BitX** ([ZipLLM](https://github.com/ds2-lab/ZipLLM), NSDI 2026) at its default zstd
91
+ level 3. ZipLLM's own code was run on the three Llama-3.1-8B fine-tunes and matched our
92
+ reimplementation (used for the other rows) or gave slightly larger output. At zstd level 19
93
+ on MetaSecAlign, BitX reaches 10.11%.
94
+ - **FM-Delta** ([NeurIPS 2024](https://github.com/ningwanyi/FM-Delta)), run from its
95
+ published C++ coder. It has no bf16 type; bf16 weights were passed as its float16 type,
96
+ which gives identical integer deltas for its sign-magnitude mapping.
97
+ - **Without a base model**, wdelta falls back to exponent coding and reaches about 66.5% on
98
+ Qwen3-8B, the same as single-model tools such as ZipNN and DFloat11. The gains above come
99
+ entirely from having the base.
100
+
101
+ All runs used a 2-vCPU machine; decode ran at about 220–240 MB/s on a typical 8B fine-tune.
102
+ The scripts in `benchmarks/` reproduce every number.
103
+
104
+ ## What makes it different
105
+
106
+ All delta compressors for fine-tunes rely on the same fact: fine-tuning moves most weights only
107
+ a little, so a fine-tune is mostly predictable from its base. They differ in how they measure
108
+ "a little" and how they encode it.
109
+
110
+ | | Difference it encodes | How it encodes it |
111
+ | --- | --- | --- |
112
+ | BitX / ZipLLM | bitwise XOR of base and fine-tune | zstd (a general-purpose byte compressor) on two byte streams |
113
+ | FM-Delta | integer difference (fpzip mapping) | range coder on the difference's bit length, low bits stored raw |
114
+ | wdelta | integer difference, in steps between adjacent bf16 values | rANS entropy coder, statistics conditioned on the base weight's exponent |
115
+
116
+ wdelta's gains come from three choices:
117
+
118
+ 1. **It measures change as a number, not as a bit pattern.** XOR is small only when the two
119
+ values share most of their bits. A weight that moves from 1.0 to 0.99609375, the very next
120
+ bf16 value below it, flips 8 of its 16 bits under XOR (`0x3F80 ^ 0x3F7F = 0x00FF`) because it
121
+ crosses a power of two. As an integer step it is simply −1. Fine-tuning moves millions of
122
+ weights across exponent boundaries, and XOR pays for every one of them.
123
+ 2. **It uses a coder built for this data.** zstd looks for repeated byte sequences, which
124
+ weight deltas rarely contain. wdelta instead counts how often each delta occurs and codes
125
+ each one with close to the minimum number of bits those counts allow (entropy coding with
126
+ rANS).
127
+ 3. **It conditions on the base weight.** The same numerical change is a different number of
128
+ steps depending on the weight's size: large weights have coarse steps, small weights fine
129
+ ones. wdelta keeps separate statistics for each base exponent, so deltas of small weights
130
+ and of large weights are each coded with their own probabilities. FM-Delta does not condition
131
+ on the base weight, and stores the low bits of each delta uncoded.
132
+
133
+ How much each choice contributes varies by model; we have not published a per-step breakdown.
134
+ The total effect is in the table above: 14–58% smaller than BitX (median 26%) and 9.5–30%
135
+ smaller than FM-Delta on the models where both ran.
136
+
137
+ ## How it works
138
+
139
+ A bf16 number is 16 bits: 1 sign bit, 8 exponent bits and 7 mantissa bits.
140
+
141
+ **1. Map each weight to an ordered integer.** Each 16-bit pattern `u` is mapped to an integer
142
+ `ord(u)` (0–65535) such that a larger float always gets a larger integer, and neighbouring
143
+ bf16 values get neighbouring integers, including across zero and across powers of two. The
144
+ mapping is one-to-one, so it is exactly reversible.
145
+
146
+ **2. Take the difference.** For each weight, `d = ord(fine-tune) − ord(base)`: the number of
147
+ bf16 steps the weight moved. Unchanged weights give 0; most changed weights give a small `d`.
148
+
149
+ **3. Turn differences into symbols.** Each `d` becomes one of 55 symbols:
150
+
151
+ - −15 to +15 each get their own symbol (31 symbols). These cover most weights.
152
+ - Larger values get a symbol for their sign and bit length (24 symbols), followed by their
153
+ remaining low bits written as-is. Those bits are close to random, so modelling them gains
154
+ almost nothing.
155
+
156
+ **4. Entropy-code the symbols, per base exponent.** Weights are processed in chunks of
157
+ 4,194,304. For each chunk, wdelta counts how often each symbol occurs for each base exponent
158
+ and stores those counts as small tables (12-bit precision, only non-zero entries). It then
159
+ codes every symbol with the table for its base weight's exponent, using rANS, an entropy coder
160
+ that spends close to the theoretical minimum number of bits for those counts. Four rANS states
161
+ are interleaved so the CPU can work on several symbols at once.
162
+
163
+ Decoding reverses the steps. The decoder already has the base, so it knows which table to use
164
+ for each weight before reading its symbol. Chunks are independent, so they are encoded and
165
+ decoded in parallel on all cores.
166
+
167
+ **Other record types.** Each tensor in a shard is stored one of four ways, whichever is
168
+ smallest:
169
+
170
+ - **Reference:** identical to the base tensor. Only its name and the base tensor's hash are
171
+ stored.
172
+ - **Delta:** the coding above, for bf16 tensors whose base has the same name and size.
173
+ - **Exponent:** for bf16 tensors with no usable base (new tensors, a resized vocabulary, or no
174
+ base at all). Exponents are entropy-coded (they carry most of the redundancy in trained
175
+ weights); the sign and mantissa bits are stored as-is. This gives the ~66.5% base-less
176
+ result.
177
+ - **Raw:** everything else (non-bf16 tensors, small tensors, the file header).
178
+
179
+ **The file.** A `.wdz` file holds the original safetensors header, one record per tensor, a
180
+ 128-bit xxh3 hash of each base tensor it depends on, and the SHA-256 of the original file. On
181
+ decode, every base tensor is hashed and compared before use, and the restored file is checked
182
+ against the SHA-256; any mismatch is an error and no output is left behind.
183
+
184
+ **Measuring it honestly.** During development, gains were estimated as cross-entropies (model
185
+ fitted on one part of a tensor, scored on another) so larger context tables could not look good
186
+ by overfitting. The final numbers in this README are actual file sizes, every one restored and
187
+ checked. `research/entropy_study.py` is the analysis script used for those estimates.
188
+
189
+ ## Prior work
190
+
191
+ wdelta does not introduce a new idea. It implements a known approach and measures it at
192
+ scale on today's bf16 models:
193
+
194
+ - **fpzip** (Lindstrom and Isenburg, 2006) maps floats to integers and codes residuals.
195
+ - **[FM-Delta](https://github.com/ningwanyi/FM-Delta)** (Ning et al., NeurIPS 2024) applies
196
+ that mapping to fine-tuned vs pre-trained weights.
197
+ - **[ULPack](https://arxiv.org/abs/2610.14184)** (Ashok, NeurIPS 2026) codes order-preserving
198
+ integer deltas with interleaved rANS conditioned on the reference weight's exponent.
199
+ wdelta's coder was developed independently and closely matches that design, so the
200
+ compression advantages above should be expected of ULPack too. We found no public ULPack
201
+ code, so it is not compared.
202
+ - **[ZipLLM / BitX](https://github.com/ds2-lab/ZipLLM)** (Wang et al., NSDI 2026) codes the
203
+ XOR of the two weights with zstd, and showed how much hub storage fine-tunes take.
204
+
205
+ What wdelta adds is engineering rather than a new method: a fast, multithreaded, open
206
+ implementation with bf16 support, a container that pins the exact base (commit and per-tensor
207
+ hashes), automatic base download, direct use with Hugging Face transformers, and prebuilt
208
+ binaries for macOS, Windows and Linux.
209
+
210
+ ## Install
211
+
212
+ **Prebuilt binaries:** download the archive for your system from the
213
+ [latest release](https://github.com/endriasf/wdelta/releases/latest) (macOS Apple Silicon and
214
+ Intel, Windows x64, Linux x64). It contains the `wdelta` command-line codec.
215
+
216
+ **Python package (whole-model pack/unpack), from source:**
217
+
218
+ ```bash
219
+ cargo build --release
220
+ mkdir -p python/wdelta/bin && cp target/release/wdelta python/wdelta/bin/
221
+ pip install ./python[hub]
222
+ ```
223
+
224
+ On Windows, copy `target\release\wdelta.exe` instead. Without the `[hub]` extra, base
225
+ models are downloaded over plain HTTPS. Requires Rust 1.85 or newer to build.
226
+
227
+ ## Use
228
+
229
+ ```bash
230
+ # compress a fine-tune against its base (local folders or Hugging Face repo ids)
231
+ wdelta-model pack my-org/my-finetune --base meta-llama/Llama-3.1-8B-Instruct -o packed/
232
+
233
+ # restore it; the base is downloaded automatically at the exact commit recorded at pack time
234
+ wdelta-model unpack packed/ -o restored/
235
+ ```
236
+
237
+ ```python
238
+ import wdelta
239
+ from transformers import AutoModelForCausalLM
240
+
241
+ path = wdelta.from_pretrained("packed/") # local folder or a Hub repo holding a packed model
242
+ model = AutoModelForCausalLM.from_pretrained(path)
243
+ ```
244
+
245
+ The low-level codec works on single safetensors files:
246
+
247
+ ```bash
248
+ wdelta encode BASE_DIR model-00001-of-00004.safetensors out.wdz # base "none" for no base
249
+ wdelta decode BASE_DIR out.wdz restored.safetensors # omit output to verify only
250
+ wdelta info out.wdz # which base a file needs
251
+ ```
252
+
253
+ `from_pretrained` unpacks once into `~/.cache/wdelta` (override with `WDELTA_CACHE`) and
254
+ returns the folder on later calls. Every restored shard is checked against the SHA-256
255
+ recorded at pack time, and every base tensor against a hash stored in the packed file, so a
256
+ wrong or modified base is rejected instead of producing a different model. Gated base models
257
+ (for example Meta's Llama) need `HF_TOKEN` set.
258
+
259
+ ## What a packed model contains
260
+
261
+ - `*.safetensors.wdz`: one compressed file per safetensors file, at the same path. A file in a
262
+ subfolder (for example `unet/`) is coded against the same subfolder of the base when the
263
+ base has one, otherwise against the base's top-level weights.
264
+ - every other file of the original, copied as-is (config, tokenizer, `.bin` files, ...)
265
+ - `wdelta.json`: the base model's repo id and commit, and the size and SHA-256 of every file.
266
+ Unpacking checks all of them.
267
+
268
+ ## Testing
269
+
270
+ ```bash
271
+ ./run_tests.sh # Rust tests, golden cross-platform check, Python tests, fuzz test
272
+ WDELTA_NET_TESTS=1 ./run_tests.sh # also packs and restores Qwen3-0.6B from the Hub (~3 GB)
273
+ ```
274
+
275
+ The tests check every one of the 65,536 bf16 values as both base and target, every possible
276
+ delta, special values (±0, ±inf, NaN, subnormals), every record type, a wrong or incomplete
277
+ base, and thousands of truncated or corrupted files, which must fail with a clear error and
278
+ leave no output behind. A golden check requires every platform to produce byte-identical
279
+ output to the reference file made on Linux. CI runs all of it on macOS (Apple Silicon and
280
+ Intel), Windows and Linux on every push.
281
+
282
+ ## License
283
+
284
+ Apache License 2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,10 @@
1
+ wdelta/__init__.py,sha256=pM8DR9eO10C0UbCI-OMnMk4fvBtoTbfkbuMI4tGN93I,9857
2
+ wdelta/__main__.py,sha256=YGhbwMl3LsJeHRr0vzDWKCjA8o-fkbkraOlnI4KHB-o,2168
3
+ wdelta/hub.py,sha256=FEauJ4qqX0kVEJrmzwKd7uDKJZAxDwkzT19ZQfAxKXc,2194
4
+ wdelta/bin/wdelta.exe,sha256=qfdCDlzfIrdpQnwkMru0Ml17Td9ppob5-TSBrWb8up0,885248
5
+ wdelta-0.3.1.dist-info/licenses/LICENSE,sha256=Pd-b5cKP4n2tFDpdx27qJSIq0d1ok0oEcGTlbtL6QMU,11560
6
+ wdelta-0.3.1.dist-info/METADATA,sha256=xk6vUDz8GucEOIB6ETi0dKJeoXUpPepdLcW5j8wWKlE,15973
7
+ wdelta-0.3.1.dist-info/WHEEL,sha256=bhMFZwp6VMtrbl2Ck6PlXryKaCggO1NzYn_HcFbBF1I,97
8
+ wdelta-0.3.1.dist-info/entry_points.txt,sha256=WxIJnRG5PnowR7kII9XrcksiRr_Qh_6t7yIamvX3XgU,54
9
+ wdelta-0.3.1.dist-info/top_level.txt,sha256=bGEPx68PDcDrE9xIG2v5nt2gIGXgd_b38hEvjb3ZHHI,7
10
+ wdelta-0.3.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-win_amd64
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ wdelta-model = wdelta.__main__:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ wdelta