Metadata-Version: 2.4
Name: deltaw
Version: 0.1.1
Summary: Version control for model weights: lossless tensor deltas, git-style history, tensor diffs and merges, sparse hot patches.
License: Apache-2.0
Project-URL: Homepage, https://github.com/tcmartin/deltaw
Project-URL: Issues, https://github.com/tcmartin/deltaw/issues
Keywords: git,version-control,checkpoints,safetensors,pytorch,model-editing,weight-space
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.22
Requires-Dist: zstandard>=0.19
Provides-Extra: torch
Requires-Dist: torch>=2.0; extra == "torch"
Provides-Extra: hf
Requires-Dist: huggingface_hub>=0.20; extra == "hf"
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: torch>=2.0; extra == "test"
Requires-Dist: safetensors; extra == "test"
Dynamic: license-file

# deltaw (ΔW)

**Version control for model weights.** Git-style commits, branches, diffs, merges and
bisect for checkpoints, with lossless tensor deltas, so a hundred edited copies of a
model cost about as much disk as one. Sparse hot patches let you apply an edit to a
live model and take it back out without reloading.

It's built for weight-space editing: you change a few columns, a rank-one direction
or a gate vector, evaluate, keep or discard, and repeat. Saving every candidate as a
full checkpoint fills a disk fast. deltaw stores what actually changed.

```
$ deltaw import runs/box-dropout-001 --branch box-dropout --verify   # output trimmed
importing runs/box-dropout-001 as series onto branch box-dropout
  ...
  checkpoint-000073728-0000.pt: 279.9 MB -> 256.6 MB
  checkpoint-000074752-0001.pt: 279.9 MB -> 43.4 MB
  ...
  checkpoint-000077824-0004.pt: 279.9 MB -> 42.8 MB
  checkpoint-000077824-0005.pt: 279.9 MB -> 212.5 KB
  ...
done: 23 commits on box-dropout; 6.2 GB read, 942.6 MB stored (6.6x) in 14s
verifying against source files ...
  55 source files match; 53 stored files rebuild to their hashes; 0 problems
```

## What it does

| | |
|---|---|
| **Lossless, byte-exact** | Every file comes back exactly as it went in, bit for bit, including PyTorch `.pt` zips. Nothing is quantized, pruned or approximated. |
| **Tensor-aware storage** | Files are split into tensors, and tensors into chunks. Each chunk is content-addressed (BLAKE2b), so identical tensors are stored once across all checkpoints. Changed chunks are stored as the smallest of: plain, XOR against the previous version, or sparse (changed indices + new values). Bytes are regrouped by significance before zstd, so float exponents compress together. |
| **Git workflow** | `init`, `add`, `commit`, `status`, `log`, `show`, `diff`, `checkout`, `branch`, `tag`, `merge`, `bisect`, `gc`, `verify`. Commits carry free-form metadata (`--meta score=0.91`) for eval results and edit rationale. |
| **Tensor diffs** | `deltaw diff A B` lists which tensors changed, how many elements, ‖ΔW‖, ‖ΔW‖/‖W‖ and max change. `--svd` adds leading singular values of each 2-D delta, so a rank-one edit shows as rank one. |
| **Element-wise merge** | A three-way merge per element: edits to different elements of the same tensor merge cleanly. Real conflicts stop the merge, unless you choose `--strategy ours`, `theirs` or `sum` (task arithmetic: base + Δours + Δtheirs). |
| **Hot patches** | `deltaw patch create A B` writes a sparse patch (indices + new values) as a `.safetensors` file. `Patch.apply(model)` writes it into a live PyTorch model in place, and the returned `Undo` restores the exact previous bits. `Patch.apply_to_vllm(llm)` patches a running vLLM engine through vLLM's own checkpoint-patch loader, and `Patch.to_vllm()` builds `SparseWeightPatch` objects for its `sparse_nccl` weight transfer. |
| **Remotes** | `push`, `fetch`, `pull` and `clone` to a directory (local disk, NAS, anything rsync-able) or a Hugging Face Hub repo (`hf://user/name`). Only missing objects move. Pushes must be fast-forwards unless forced, and `clone --depth 1` fetches just the latest version. |
| **Import existing piles** | `deltaw import DIR` turns a directory of checkpoints into history without copying anything into a working tree. Each file becomes one commit (or each subdirectory one commit, for HF Trainer layouts), each delta-encoded against the previous one. |
| **Works with git** | `deltaw git-setup` makes plain `git diff` show per-tensor changes for `.safetensors` / `.pt` files. |

Text files (configs, notes, eval JSON) are tracked like any other file, with normal
unified text diffs.

## Measured on real checkpoints

Hardware: 4-core desktop CPU, NVMe, nothing on the GPU. All results lossless and verified by rebuilding
every file.

**Weight-space edit loop, Qwen3.5-2B (4.55 GB bf16 safetensors).** 24 candidate edits:
scaling 128 or 512 writer columns of an MLP `down_proj` at three strengths, dense
rank-one updates, and 1-D `A_log` gate edits, each on its own branch.
([benchmarks/wsp_edit_loop.py](https://github.com/tcmartin/deltaw/blob/main/benchmarks/wsp_edit_loop.py))

| edit | elements changed | stored | time to commit |
|---|---:|---:|---:|
| scale 128 columns | 262,144 | 0.27–0.36 MB | 0.1–0.3 s |
| scale 512 columns | 1,048,576 | 0.92–1.44 MB | 0.2 s |
| rank-one ΔW = αuvᵀ on a whole 2048×6144 matrix | ~11.9 M | ~13.9 MB | 0.5 s |
| 4 entries of `A_log` | 4 | < 1 KB | < 0.1 s |
| base model itself | – | 3.12 GB (from 4.55 GB) | 10 s |

Base plus 24 candidates: 113.7 GB of model files stored in 3.2 GB (35.8x). `deltaw
verify` checked all 25 versions in 22 s.

**Training run with LoRA adapters, frozen heads and optimizer state.** 22 checkpoints
of 280 MB plus sidecar files: 6.2 GB → 943 MB (6.6x) in 14 s. Frozen tensors are
stored once; a few "different" checkpoints turn out to be identical in content and
cost about 200 KB each.

**Worst case: every element changes.** 43 checkpoints of a LoRA run where adapters and
optimizer moments all move each step: 11.3 GB → 6.4 GB (1.8x) at 346 MB/s.

**Live hot patch, Qwen3.5-0.8B in transformers.** Patching 262,144 elements of one
`down_proj` took 20 ms in place on CPU; reverting took 0.7 ms. After the revert, every
parameter and the output logits were bit-identical to the original.
([benchmarks/live_hotpatch.py](https://github.com/tcmartin/deltaw/blob/main/benchmarks/live_hotpatch.py))

**Hot patch inside vLLM, Qwen3.5-0.8B on an RTX 3090.** A deltaw patch (327,680
elements in one `down_proj` and in `gate_proj`, which vLLM fuses into `gate_up_proj`)
applied to a running vLLM 0.34 engine in 80 ms. Greedy outputs and top-5 logprobs on
four prompts then matched a fresh vLLM load of the edited checkpoint exactly. The
reverse patch (7 ms) brought them back to exactly the original.
([benchmarks/vllm_live.py](https://github.com/tcmartin/deltaw/blob/main/benchmarks/vllm_live.py))

**A real 709 GB pile.** 103 training-run directories (Qwen3.5 adapter and head
experiments plus one DINOv2 vision run: LoRA adapters, trained heads, optimizer
state, feature caches, configs), imported into one store with one branch per run:
709 GB → 333 GB (2.1x). Every file was rebuilt from the store and compared byte for
byte with its original before the originals were deleted, and a full `deltaw verify`
afterwards found 0 problems. Most of these runs update adapters and optimizer
moments on every step, so this is close to the dense worst case below. The best runs
reached 3–4x; runs that are mostly a single checkpoint got 1.2–1.5x.

What it can't do: when every element changes (full fine-tuning, optimizer moments),
lossless storage only gets about 1.8x. There's no free lunch for dense, noisy
updates, and deltaw doesn't pretend otherwise. The big wins come from tensors that
don't change, checkpoints that repeat, and edits that are sparse or low-precision.

## Install

```bash
pip install deltaw            # numpy + zstandard
pip install "deltaw[torch]"   # for hot patches and --svd
```

or from source: `pip install -e .`

## Quick start

```bash
deltaw init
deltaw add model.safetensors config.json notes.md
deltaw commit -m "base model"

# ... edit weights in place (any tool), then
deltaw diff                            # which tensors changed, by how much
deltaw commit -a -m "L9: scale 128 writer columns x1.5" --meta mmlu=0.612

deltaw checkout -b try-rank1 HEAD~1    # branch from the base
deltaw log --oneline
deltaw show --svd                      # what the last commit changed, with singular values
deltaw checkout main -- model.safetensors   # restore one file from a branch
```

Turning an existing pile into history:

```bash
deltaw import /data/runs/my-run --verify          # one commit per checkpoint file
deltaw import /data/sweeps/edits --mode subdirs   # one commit per subdirectory
deltaw stats
deltaw export my-run~3 checkpoint-0042.pt -o /tmp/ckpt.pt   # rebuild any version
```

`import` never deletes or modifies your files. Once `--verify` reports 0 problems,
deleting the originals is your call.

## Editing loops in Python

```python
from deltaw import Repo, Patch, commit_patch

repo = Repo.open("my-model-repo")      # HEAD has model.safetensors

before = {name: W.clone()}             # the tensors you are about to edit
edit(model)                            # your weight-space edit
after = {name: model.get_parameter(name).detach()}

patch = Patch.from_state_dicts(before, after)       # exact, sparse
cid = commit_patch(repo, patch, "model.safetensors",
                   "L9: scale 128 columns", meta={"score": 0.61})
# only the touched chunks are written; the full model is never re-serialized
```

Trying a candidate on a live model and always rolling back:

```python
patch = Patch.load("candidate.safetensors")      # from `deltaw patch create A B -o ...`
with patch.applied(model):                       # in place, no reload
    score = evaluate(model)
# weights are bit-identical to before here, even if evaluate() raised
```

Switching a loaded model between commits without reloading it:

```python
from deltaw import LiveCheckout

live = LiveCheckout(repo, model, "main", path="model.safetensors")
live.switch("try-rank1")    # writes only the elements that differ between the commits
live.switch("main")         # back to the exact original bits
```

Patches *set* values rather than adding deltas, so switching back and forth never
accumulates bf16 rounding error.

### vLLM

Patching an offline `vllm.LLM` engine in place (start Python with
`VLLM_ALLOW_INSECURE_SERIALIZATION=1`, which lets the loader be sent to vLLM's worker
process):

```python
llm = LLM(model="my-model-dir")
patch = Patch.between(repo, "main", "try-rank1", path="model.safetensors")
patch.apply_to_vllm(llm)        # vLLM's own load_checkpoint_weight_patches: handles fused/packed params
...
Patch.between(repo, "try-rank1", "main", path="model.safetensors").apply_to_vllm(llm)  # revert
```

For a trainer driving a separate vLLM server with the `sparse_nccl` weight-transfer
backend:

```python
engine.send_weights(patch.to_vllm())   # SparseWeightPatch: int32 flat indices, new values, full_shape
```

Names are Hugging Face checkpoint names, which they are for safetensors commits. vLLM
patches support floating-point tensors, and parameters whose loaders transform the
values (rather than copying them) are rejected by vLLM itself. The in-engine path is
tested on a GPU (above). The `sparse_nccl` objects pass vLLM's own validator, but the
NCCL broadcast between processes needs two GPUs and hasn't been run here.

## Sharing: remotes

```bash
deltaw remote add origin /mnt/nas/models/qwen-edits    # or hf://you/qwen-edits
deltaw push                      # current branch; --tags, --force
deltaw clone /mnt/nas/models/qwen-edits work           # or: deltaw clone hf://you/qwen-edits
deltaw clone hf://you/qwen-edits --depth 1             # latest version only
deltaw pull                      # fetch + fast-forward or element-wise merge
```

Hugging Face remotes need `pip install huggingface_hub` and a token with write
access for pushing. A new Hub repo is created private unless you pass `--public`.

## Finding the edit that broke something

```bash
deltaw bisect start main base
deltaw bisect run "python eval.py --threshold 0.6"   # exit 0 = good, 1 = bad, 125 = skip
deltaw bisect reset
```

## How it works

```
commit ──> tree ──> file manifest ──> segments ──> chunks (content-addressed)
                     (format, size,     tensor: name, dtype, shape
                      Merkle root)      glue:   headers, pickles, zip records
```

* **Parsing without loading.** safetensors headers give names, dtypes and offsets.
  PyTorch `.pt` files are uncompressed zips: each storage record becomes a tensor
  segment, and tensor names are recovered by walking `data.pkl` with a stub unpickler
  that never runs code from the file. Everything else (headers, pickles, zip
  directories) is kept verbatim as glue, so concatenating segments rebuilds the
  original bytes exactly.
* **Chunks** are at most 32 MB, cut at element boundaries. A one-row edit to a
  1 GB embedding rewrites one chunk, not the tensor.
* **Deltas** are taken against the chunk at the same position of the same tensor in
  the previous version. XOR keeps the sign and exponent bits that didn't change as
  zero runs, and sparse coding stores only changed elements. Delta chains are capped
  at depth 24, like git's pack depth.
* **Integrity.** Every decoded chunk is checked against its BLAKE2b id. A file is
  identified by the Merkle root of its chunk ids, so committing a patch is O(edit)
  rather than O(model). `deltaw verify` rebuilds everything.

Repository layout: `.deltaw/objects/ab/cdef…` (one file per object), `refs/heads`,
`refs/tags`, `HEAD`, `index.json`, much like `.git`.

## Why not git-lfs / git-theta / Xet / DVC?

* **git-lfs, DVC** store whole files: every checkpoint is a new full copy.
* **Hugging Face Xet** deduplicates byte chunks across uploads. That's great for
  unchanged files, but a fine-tune or an edit that touches every 64 KB region of a
  tensor defeats it, and it doesn't know what a tensor is (no tensor diffs, merges
  or patches).
* **[git-theta](https://github.com/r-three/git-theta)** (ICML 2023) is the closest
  prior work and inspired parts of this design: per-parameter-group tracking, sparse
  and low-rank updates, merges. It works through git clean/smudge filters and LFS;
  it hasn't been updated since 2024.
* **Upstreaming into git itself** isn't realistic: git's object model and delta
  compression are byte-oriented by design. Its extension points (diff drivers,
  filters) are the right place to plug in, which `deltaw git-setup` does.

deltaw keeps its own object store to get element-aware deltas, byte-exact rebuilds of
`.pt` files, O(edit) patch commits, and an import path that doesn't push 500 GB
through a git filter.

## Status

v0.1, alpha. The on-disk format may still change before 1.0. Tested: 28 unit tests,
plus the real-checkpoint benchmarks above. The Hugging Face transport is implemented
but not yet tested end to end against the Hub. Not done yet:

- packfiles (many tiny objects become many tiny files)
- converting dense 2-D deltas to LoRA adapters via truncated SVD (lossy, opt-in)
- best-parent search when importing unordered checkpoints
- GGUF-aware parsing (GGUF files are stored as generic chunked blobs today)

## License

Apache-2.0
